C# method extension

1 Introduction

Extension methods are C#3.0new features introduced that allow you to add new methods to an existing class without modifying the code of the original class or creating an inheritance relationship.

2. Features

  1. When defining method extension, you need to define it as a static class (static class)
  2. The first parameter of method expansion must be the type to be expanded, thismarked with keywords. This parameter represents the instance on which the extension method is called.
  3. The namespace in which the method extension is located should be imported into the code file that uses the extension method.

3. Example

namespace ExtensionMethodsExample
{
    
    
    public static class IntExtensions
    {
    
    
        // 方法拓展:计算整数的平方
        public static int Square(this int num)
        {
    
    
            return num * num;
        }
        
        // 方法拓展:计算整数的平方,再加上某个值
	    public static int SquareAdd(this int num, int add)
	    {
    
    
	        return num * num + add;
	    }
    }

    class Program
    {
    
    
        static void Main()
        {
    
    
            int number = 5;
            int result = number.Square(); // 使用方法拓展
            int result1 = number.SquareAdd(1)	// 带参数的方法拓展
            Console.WriteLine("Square of {0} is {1}", number, result);
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_45136016/article/details/132080099