this 使用

为什么这里会有一个this关键字,做什么用?其实这就是扩展方法!这个扩展方法在静态类中声明,定义一个静态方法,其中第一个参数定义可它的扩展类型。Foo()方法扩展了String类,因为它的第一个参数定义了String类型,为了区分扩展方法和一般的静态方法,扩展方法还需要给第一个参数使用this关键字。

现在就可以使用带string类型的Foo方法了:

string s="Hello"; s.Foo();

结果在控制台上显示Foo invoked for Hello ,因为Hello是传送给Foo方法的字符串。

 class Program
    {
        static void Main(string[] args)
        {
            string s = "Hello";  s.Foo();    //s 为扩展方法
            StringExtension.Foo(s);       //
            Console.ReadKey();
        }
        
    }
    public static class StringExtension
    {
        public static void Foo(this string s)       //this 为扩展方法
        {
            Console.WriteLine("Foo invoked for {0}", s);
        }
        public static void Foo(string s)            //普通方法
        {
            Console.WriteLine("Foo invoked for {0}", s);
        }
    }
原文地址:https://www.cnblogs.com/laopo/p/13799820.html