yekun

导航

C#3.0 扩展方法

  扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。对于用 C# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。

 static void Main(string[] args)
        {
            string str = "".plusString(p => p = p + " girl: lisi、lili\r\n");
            Console.WriteLine(str);

            Console.Read();
        }
    

    static class aaa
    {
        public static string plusString<TParam>(this TParam source, Func<TParam, string> func)
        {
            Console.WriteLine("字符串相加前原值为:{0}。。。。。。", source);
            return func(source);
        }
    }

在代码中,可以使用实例方法语法调用该扩展方法。但是,编译器生成的中间语言 (IL) 会将代码转换为对静态方法的调用。因此,并未真正违反封装原则。实际上,扩展方法无法访问它们所扩展的类型中的私有变量。

详细参考博客 C#原始类型扩展方法—this参数修饰符

posted on 2016-01-11 15:07  yekun  阅读(166)  评论(0编辑  收藏  举报