zoukankan      html  css  js  c++  java
  • C#4.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"));

  • 相关阅读:
    彻底禁用resource manager
    NYOJ_94 cigarettes 递归VS迭代
    itunes connect上传截图提示无法加载文件问题
    hdu 1165 Eddy's research II(数学题,递推)
    USACO holstein 超时代码
    金蝶KIS标准版与金蝶K3的差别
    OC第三天(内存管理)
    HDU 1059 Dividing(多重背包)
    说说參数传递(泛型托付)
    Json数组操作小记 及 JSON对象和字符串之间的相互转换
  • 原文地址:https://www.cnblogs.com/zhouhb/p/2088777.html
Copyright © 2011-2022 走看看