In practical applications, developers completeCodeAfter compilation, unless the changed code is re-compiled, it is difficult for developers to add new functions to the original code.
In C #3.0, a new extension feature is provided to enable developers to compileProgramAdd related methods in the set to easily expand the original functions.
1. Definition of extension methods
When defining an extension method, the extension method must first be defined in a static class. So this extension method must be a static method. Second, in the parameter list of the extension method, you need to add the keyword "this" before the first parameter type as the modifier, followed by the name of the extension class. As follows:
Code: Extension Method Definition
Static ClassMyextensions {Public Static StringGetassemblyname (This ObjectOBJ ){ReturnOBJ. GetType (). Name ;}}
In the above Code, a static class myextension is defined, and an extension method getassemblyname () is defined (). In the parameter list of this method, the keyword "this" is used to modify the object type and associate the extension method with the object. Therefore, you can use the getassemblyname () method to extend the object method for any object and classes that inherit the object class.
2. Use of extension methods
By using the extension method, you can call the extension method of the object of association type instantiation, or directly call the Extension Method in the static class, where the method parameter inputs the association type.
Code: Extended method of instantiating objects
Static VoidMain (String[] ARGs ){ObjectOBJ =New Object(); Obj. getassemblyname ();}
The Code defines an object-type parameter OBJ, and calls the extension method getassemblyname Of The OBJ type to obtain the Assembly name.
When writing code, in the vs environment, developers can use only perceptible functions to easily select extension methods, as shown in:
In addition, you can add extension methods for generic types so that developers can use extension methods in the formulated generic classes. I am not very familiar with generic models, so I am not explicit at the moment.
Technorati label: Extension Method