This article was reproduced from: http://blog.csdn.net/zxz414644665/article/details/9793205
When you have a requirement like this, the extension will work: In the project, Class A needs to add functionality, and we think of adding a public method to Class A, which is obviously possible, but for some reason you can't modify the code of Class A itself, but it does need to add functionality to Class A, What to do? This time the extension method (Extension Methods) will help you to complete the above functions. Here are some examples:
Class A: For simplicity, there is only one own method in Class A.
using System; namespace testapp.method{ publicclass Test { publicvoid TestMethod () { Console.WriteLine ("publicvoid TestMethod () "); } }}
Now I need to add a method to Class A, but I can't modify Class A, so let's add an extension method (Extension Methods) as follows:
using System; using Testapp.method; namespace testapp.extensionmethod{ publicstaticclass extendclass { Public Static void Extendmethod ( this test test) { Console.WriteLine ("test. Extendmethod ()"); }}
In fact, the extension method (Extension Methods) certainly needs a class wrapper, so we have to have a class, note that this class must be a static class, and the extension method (Extension Methods) must also be a static method, The parameter of the method must have an extended class as one of the parameters, which is decorated with the this keyword before.
Well, so that our extension is done, we can call this extension method with an instance of Class A, as follows:
usingSystem;usingTestapp.extensionmethod;usingTestapp.method;namespacetestapp{Static voidMain (string[] args) {test test=NewTest (); Test. TestMethod (); //Call the method of itselfTest. Extendmethod ();//Call the extension method }}
Here, as long as the using extension method (Extension Methods) is located in the namespace, this extension method (Extension Methods) can be invoked through an instance of Class A.
In addition, MSDN has an article specifically about this, you can go to see: Extension Methods.
Go C #-Application of extension methods (Extension Methods)