Linq学习知识摘记

扩展方法

扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 仅当您使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。定义扩展方法需要注意,只能在静态类中定义并且是静态方法,如果扩展方法名和原有方法名发生冲突,那么扩展方法将失效

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
 
//引入命名空间
using ExtensionMethods;

//调用扩展方法
string s = "Hello Extension Methods";
int i = s.WordCount();
 
原文地址:https://www.cnblogs.com/shijun/p/2855097.html