C# extension methods

Usually, we want to add methods to a type, which can be done in the following two ways:

  • Modify the source code.
  • Define new methods in derived classes.

But the above method is not omnipotent. We cannot guarantee that we have the source code of a type, nor can we guarantee that this type can be inherited by us (such as structure, enumeration, String, etc.). But C# provides a way, that is, extension method. Using extension methods, you can directly "add" methods to existing types without modifying the source code of the type. , and there is no need to use a derived class to implement the method.

1. What is an extension method?

Extension methods enable you to "add" methods to an existing type without having to create a new derived type, recompile, or otherwise modify the original type.

2. Extension method structure

  • The class in which the extension method is located must be declared static.
  • Extension methods must be declared public and static.
  • The first parameter of an extension method must contain the keyword this, followed by the name of the extended class.

extension method

3. Examples

1. Implement a method to convert string to int type.
/// <summary>
/// 扩展方法
/// </summary>
/// 
public static class ExpandMethod
{
    
    
    /// <summary>
    /// 将字符串转换为int
    /// </summary>
    /// <param name="str"></param>
    /// <returns>失败返回0</returns>
    public static int StringToInt(this string str)
    {
    
    
        int.TryParse(str, out var res);
        return res;
    }
}

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Console.WriteLine("2" + 1);
        Console.WriteLine("2".StringToInt() + 1);
        Console.WriteLine("string".StringToInt());
    }
}

Output result:

21
3
0
2. Add two numbers
/// <summary>
/// 扩展方法
/// </summary>
/// 
public static class ExpandMethod
{
    
    
    /// <summary>
    /// 两个数相加
    /// </summary>
    /// <param name="num"></param>
    /// <param name="num2"></param>
    /// <returns></returns>
    public static int Sum(this int num,int num2)
    {
    
    
        return num + num2;
    }
}

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Console.WriteLine(3.Sum(2));
    }
}

Output result:

5
3. The extension method has the same signature as the extended type
public class MyClass
{
    
    
    public void MethodA()
    {
    
    
        Console.WriteLine("MyClass.MethodA");
    }

    public void MethodB()
    {
    
    
        Console.WriteLine("MyClass.MethodB");
    }

    public void MethodC()
    {
    
    
        Console.WriteLine("MyClass.MethodC");
    }

    public void MethodD(int num)
    {
    
    
        Console.WriteLine("MyClass.MethodD");
    }
}

/// <summary>
/// 扩展方法
/// </summary>
/// 
public static class ExpandMethod
{
    
    
    public static void MethodB(this MyClass myClass)
    {
    
    
        Console.WriteLine("ExpandMethod.MethodB");
    }

    public static string MethodC(this MyClass myClass)
    {
    
    
        return "ExpandMethod.MethodC";
    }

    public static void MethodD(this MyClass myClass,int num)
    {
    
    
        Console.WriteLine("ExpandMethod.MethodD");
    }

    public static void MethodE(this MyClass myClass)
    {
    
    
        Console.WriteLine("ExpandMethod.MethodE");
    }

}

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        MyClass myClass = new MyClass();
        myClass.MethodA();
        myClass.MethodB();
        myClass.MethodC();
        myClass.MethodD(1);
        myClass.MethodE();
    }
}

operation result:

MyClass.MethodA
MyClass.MethodB
MyClass.MethodC
MyClass.MethodD
ExpandMethod.MethodE

You can see from the running results that if the extended method has the same signature as the extended type, the method will never be called.

4. Attention

Note:
If the extended method has the same signature as the extended type, the method will never be called.

For more information about extension methods, please refer to Official documentation

Supongo que te gusta

Origin blog.csdn.net/weixin_39520967/article/details/122659327
Recomendado
Clasificación