So what is the role of the extension method? Many times we want to extend some functions for an existing class, but there is no need to inherit the class. Sometimes this class does not allow inheritance at all, such as the string class, in this case, you can use the extension method to expand its functions.
The following is an example:
1. Create a class library as follows:
Code:
-
- UsingSystem;
-
- UsingSystem. Collections. Generic;
-
- UsingSystem. LINQ;
-
- UsingSystem. text;
-
-
- NamespaceMethodextendclasses
-
- {
- // This class does not play any role, but loads methods into the memory at runtime.
-
- Public Static ClassExtendsstring
-
- {
-
- // Use the this keyword to modify the string keyword, indicating that this method is a string extension method.
- Public Static StringSpacetounderline (This StringSource)
-
- {
-
- Char[] Chars = source. tochararray ();
-
- StringTemp ="";
- Foreach(CharCInChars)
-
- {
-
- If(Char. Iswhitespace (c ))
-
- Temp + ="_";
- Else
-
- Temp + = C;
-
- }
-
- ReturnTemp;
-
- }
-
- }
-
- }
Then compile.
2. Create a test ConsoleProgram, Add a reference to the previous project, and thenCodeModify as follows:
Code:
-
- UsingSystem;
-
- UsingSystem. Collections. Generic;
-
- UsingSystem. LINQ;
-
- UsingSystem. text;
-
- UsingMethodextendclasses;// This namespace is where the extension method is located
-
NamespaceLeleapplication1
-
- {
- ClassProgram
-
- {
-
- Static VoidMain (String[] ARGs)
-
- {
-
- StringSTR ="ABC dd TT";
- STR = Str. spacetounderline ();// The spacetounderline () method is the extension method we added for the string. It seems that the string class has multiple methods. In fact, we do not actually operate the string class.
-
- Console. writeline (STR );
-
- }
-
- }
-
- }
Compile and run the program. The result is abc_dd_tt. It indicates that the spacetounderline () method plays a role.
Summary
Pay attention to the following points during method extension:
1. The class where the extension method is located must be static and must be defined on top-level static classes.
2. The extension method must be static.
3. The parameter type of the extension method must be the type to be extended.
4. The this keyword must be added before the parameter type.
Original address:
http://student.csdn.net/space.php? Uid = 1068338 & Do = Blog & id = 43677