The extension method is actually the syntax feature introduced in C #3.0 (I am out ). By using the extension method, you can add a method to an existing type "dynamic" without creating a new derived type or modifying the source code of the original type.
There are the following primitive types:
Class mymath
{
Public int add (int A, int B)
{
Return A + B;
}
}
Add "Extension Method"
Static class mymathextend
{
Public static int sub (this mymath math, int A, int B)
{
Return A-B;
}
}
Call the added "Extension Method ":
Mymath math = new mymath ();
Console. writeline (math. sub (5, 3 ));
We can see that the original class mymath is not modified, but a new method sub is added for it.
Key points for using the extension method:
(1) The extension method must be static and put in a non-generic static class. So the above mymathextend class adds the modifier static, And the sub method is also static;
(2) The first parameter of the extension method must have the this keyword before it specifies the type of object to which the extension method will be "appended.
You can also add extension methods for existing classes in the. NET class library. For example, add an extension method for the string class in. Net:
Static class stringextend
{
Public static string append (this string S, string Str)
{
Stringbuilder strb = new stringbuilder (s );
Strb. append (STR );
Return strb. tostring ();
}
}
Call the extension method added for the string class:
String S = "AA ";
Console. writeline (S. append ("BB "));