C#扩展方法

扩展方法能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但它是通过实例 方法语法进行调用的。它的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。仅当您使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。

为 System.String 类定义的一个扩展方法。请注意,它是在非嵌套、非泛型静态类内部定义的:

 

namespace ExtensionMethods

{

    public static class MyExtensions

    {

        public static int WordCount(this String str)

        {

            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;

        }

    }   

}

使用sttring的这个扩展方法

using ExtensionMethods;



...

string s = "Hello Extension Methods";

int i = s.WordCount();

 

你可能感兴趣的:(C#)