C# 扩展方法

C#扩展方法主要用于对封装好的类库进行功能扩展,一种非常重要的技术手段,典型应用 LINQ。

要点:

1.  类名格式 ClassTypeExtension;例如,要对 Double 类扩展,则类型名称为DoubleExtension;

2. 所扩展的方法必须是公有、静态的,即 public static修饰;

3. 方法的形参列表中的第一个参数必须由 this 修饰;

例子,

class Program
{
    static void Main(string[] args)
    {
        double x = 2.718181828549;
        x = x.RoundUp(3);
        Console.WriteLine("x's RoundUp is {0}", x);
    }
}

static class DoubleExtension{
    public static double RoundUp(this double x, int n)
    {
        double k = 0.4;//指定位非零,即向上舍入
        for(int i = 0; i < n; i++)
        {
            k *= 0.1;
        }
        return Math.Round(x + k,n);
    }
}

 

  

 

posted @ 2020-03-01 12:27  神棍二叔  阅读(211)  评论(0编辑  收藏  举报