扩展方法浅谈

扩展方法就是能让我们能够像现有的类型添加方法,而无须修改原有的类型,扩展方法必须定义为静态的,因此声明时必须使用static关键字,调用的时候 可以像扩展类型上的实例方法一样进行调用。再声明的时候,传入的参数,至少应该带一个 this关键字,将传入的参数当做自身来使用。
class Program
    {
        static void Main(string[] args)
        {
            string s = " Hello,world! ";
            Console.WriteLine(s.GetWordCount());   
//因为是静态,所以可以直接调用扩展类的方法          
        }
    }
    static class ExString    //必须使用static关键字
{
        public static int GetWordCount(this string s)  
    //必须使用this关键字将参数传入,必须使用static关键字,定义成静态方法。
        {
            return s.Split(' ', ',', '.', '"','!','?' ).Length;
        }
}

你可能感兴趣的:(职场,休闲,扩展方法)