C#小轮子:扩展方法

相关资源

前言

我们知道传统的方法增加是C#类继承。A->B->C。一层一层继承下去,然后重写父类的方法。这个适合传统开发,即知道层次关系的开发。

扩展方法是 A+A_Extend,适合灵活开发,添加扩展内容

扩展方法示例

声明扩展方法

namespace ExtensionMethods
{
    
    
    public static class MyExtensions
    {
    
    
    //this指向扩展的类型,是一个class类对应一个扩展方法
        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();//这里调用了WordCount的扩展方法

注意:

扩展方法无法扩展已有的命名空间。比如A原本就有A.method(),添加method扩展则无效

相关资源

猜你喜欢

转载自blog.csdn.net/qq_44695769/article/details/132341295