C#3.0新特性:扩展方法

扩展方法其实是C#3.0就引入的语法特性(本人out了)。通过使用扩展方法,可以在不创建新的派生类型、不修改原始类型的源代码的情况下,向现有类型“动态”添加方法。

   有如下的原始类型:

    class MyMath
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

  添加“扩展方法”

    static class MyMathExtend
    {
        public static int Sub(this MyMath math, int a, int b)
        {
            return a - b;
        }
    }

 调用添加的“扩展方法”:

     MyMath math = new MyMath();
     Console.WriteLine(math.Sub(5, 3));

可以看到,没有修改原始类MyMath,但却为它添加了新的方法Sub。

扩展方法使用要点:

(1)扩展方法必须是静态的,且必须放在一个非泛型的静态类中。所以上面的MyMathExtend类加了修饰符static,且Sub方法也为静态的;

(2)扩展方法的第一个参数前必须有this关键字,指定此扩展方法将“附加”在哪个类型的对象上。

我们也可以为.Net类库中的已有类添加扩展方法。如为.Net中的string类添加扩展方法:

    static class StringExtend
    {
        public static string Append(this string s, string str)
        {
            StringBuilder strb = new StringBuilder(s);
            strb.Append(str);
            return strb.ToString();
        }
    }

调用为string类添加的扩展方法:

    string s = "aa";
    Console.WriteLine(s.Append("bb"));

原文地址:https://www.cnblogs.com/iwangjun/p/2430571.html