From MSDN: the best. NET Learning Library https://msdn.microsoft.com/zh-cn/library/gg145045%28v=vs.110%29.aspx
Extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type.
An extension method is a special static method, but it can be called just like an instance method on an extended type.
this modifier. " > Their first parameter specifies which type the method acts on, and the parameter is prefixed with the This modifier.
this modifier. " > system. The String class. The following example shows an extension method defined for the System.String class. Note that it is defined internally in a non-nested, non-generic static class: for example:
Public Static classMyExtensions { Public Static intWordCount ( ThisString str) { returnStr. Split (New Char[] {' ','.','?'}, Stringsplitoptions.removeemptyentries). Length; } }
You can use this using directive to place the WordCount extension method in scope:
using Extensionmethods;
Also, you can invoke the extension method from the application using the following syntax:
string " Hello Extension Methods " ; int i = S.wordcount ();//Results: 21
In code, you can call the extension method using the instance method syntax. However, the compiler-generated intermediate language (IL) translates the code into a call to a static method. Therefore, the encapsulation principle is not really violated. In fact, extension methods cannot access private variables in the types they extend.
How to define and invoke extension methods