When you have the following requirement, the extension method will play a role: in the project, Class A needs to add a function, and we think of adding a public method to Class, this is obvious, but for some reason, you cannot modify the code of Class A, but you must add functions to Class A. What should I do? At this time, the extension methods will help you complete the above functions. The following is an example:
Class A: For simplicity, Class A has only one method of its own.
using System;namespace TestApp.Method{ public class Test { public void TestMethod() { Console.WriteLine("public void TestMethod()"); } }}
Now I need to add a method to Class A, but I cannot modify Class A. Well, let's add an extension method (extension methods) as follows:
using System;using TestApp.Method;namespace TestApp.ExtensionMethod{ public static class ExtendClass { public static void ExtendMethod(this Test test) { Console.WriteLine("test.ExtendMethod()"); } }}
In fact, extension methods requires a class packaging, so we must have a class. Note that this class must be a static class and extension methods) it must also be a static method. The extension class must be included in the method parameter as one of the parameters. This parameter must be prefixed with the this keyword.
Okay, so that our extension is complete. Now we can call this extension method through an instance of Class A, as shown below:
using System;using TestApp.ExtensionMethod;using TestApp.Method;namespace TestApp{ static void Main(string[] args) { Test test = new Test(); test.TestMethod(); // Call the method of itself test.ExtendMethod(); // Call the extension method }}
Here, as long as the namespace of the using Extension Method (extension methods) can call this extension method (extension methods) through an instance of Class.
In addition, msdn has an article dedicated to this. You can go and see:
Extension methods.