C# Tiny Wheels: Extension Methods

related resources

foreword

We know that the traditional way to increase is C# class inheritance. A->B->C. Inherit layer by layer, and then override the method of the parent class. This is suitable for traditional development, that is, development that knows the hierarchical relationship.

The extension method is A+A_Extend, which is suitable for flexible development and adding extended content

Extension method example

Declaring an extension method

namespace ExtensionMethods
{
    
    
    public static class MyExtensions
    {
    
    
    //this指向扩展的类型,是一个class类对应一个扩展方法
        public static int WordCount(this string str)
        {
    
    
            return str.Split(new char[] {
    
     ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}

use extension method

//引入扩展命名空间
using ExtensionMethods;
......

string s = "Hello Extension Methods";
int i = s.WordCount();//这里调用了WordCount的扩展方法

Notice:

Extension methods cannot extend an existing namespace. For example, A originally has A.method(), adding method extension is invalid

related resources

Guess you like

Origin blog.csdn.net/qq_44695769/article/details/132341295