The usage is as follows:Public static class classhelper <br/>{< br/> // use this to declare and attach this method to the student object <br/> Public static bool checkname (this student Stu) <br/>{< br/> If (Stu. name = "James") <br/>{< br/> return true; <br/>}< br/> else <br/> return false; <br/>}< br/> // Add a changestring Method to the string object <br/> Public static string changestring (this string S, string Str) <br/>{< br/> return STR + ":" + S; <br/>}</P> <p> public class student <br/>{< br/> Public string name {Get; set ;} </P> <p> Public void show () <br/>{< br/> This. checkname (); // student has the checkname method </P> <p >}< br/> Public void showstring () <br/>{< br/> string S = "AAA"; <br/> S. changestring ("Haha"); // string has the changestring method <br/>}< br/>},
This example is very simple. A checkname method is extended for the custom student class. This method has no parameters, and then a changestring method is extended for the class that comes with the string system, this method has a string type parameter. Note: The extension method must be declared as a static method and put in a static class.
This not only extends class methods, but also extends interfaces, so that any class inherited from this interface will have this extension method. Here we modify the above example:
Public static class classhelper <br/>{< br/> // use this to declare and attach this method to the istudent object <br/> Public static bool checkname (this istudent Stu) <br/>{< br/> If (Stu. name = "James") <br/>{< br/> return true; <br/>}< br/> else <br/> return false; <br/>}< br/> // Add a changestring Method to the string object <br/> Public static string changestring (this string S, string Str) <br/>{< br/> return STR + ":" + S; <br/>}</P> <p> Public interface istudent <br/>{< br/> Public void show (); <br/> Public string name {Get; Set ;}< br/>}</P> <p> public class studenta: istudent <br/>{</P> <p> Public void show () <br/>{< br/> This. checkname (); // student has the checkname method </P> <p >}< br/> Public void showstring () <br/>{</P> <p> string S = "AAA"; <br/> S. changestring ("Haha"); // string has the changestring method </P> <p >}< br/>}</P> <p> public class studentb: istudent <br/>{</P> <p> Public void show () <br/>{< br/> This. checkname (); // student has the checkname method </P> <p >}< br/> Public void showstring () <br/>{< br/> string S = "AAA"; <br/> S. changestring ("Haha"); // string has the changestring method </P> <p >}< br/>}Note that the checkname in this example is changed from this student to this istudent, and istudent is an interface. Both studenta and studentb inherit this interface and they all have the checkname extension method.
Obviously, this is advantageous. When a third party provides you with a DLL, including many classes, because these classes are encapsulated in the DLL, when you want to expand a class, you cannot modify the source code of the class. In this case, you can use this to expand ....