In practical applications, after the developer completes code compilation, it is difficult for the developer to add new functions to the original code unless the modified Code is re-compiled.
In C #3.0, a new feature of the extension method is provided, which allows developers to add related methods in the compiled assembly, so as to easily extend the original functions.
1. Definition of extension methods
When defining an extension method, the extension method is first defined in a static class (automatically loaded when the Assembly is loaded), so this extension method must also 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 class MyExtensions { public static string GetAssemblyName(this object obj) { return obj.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 void Main(string[] args) { object obj = 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.