The purpose of the extension method is to add a method to an existing type, such as the following code, which adds a method of turning into a shape for string strings.
In this way, you can add some other methods to refine the code for many existing types.
The following example shows the definition of an extension method to use.
classProgram {Static voidMain (string[] args) {Console.Write ("1". ToInt ()); Console.read (); } } Public Static classextendsion { Public Static intToInt ( This stringstr) { returnConvert.ToInt32 (str); } }
View Code
Extension method definition Note points:
1. The class where the extension method definition resides must be statically static.
2. The extension method definition must be static.
3. The first parameter of the extension method is the type to be extended, which is placed after the This keyword.
4. The. NET version is 3.0 or 2.0 error (errors below), only 3.5 and later can be used directly
Error 1 could not define a new extension method because the type "System.Runtime.CompilerServices.ExtensionAttribute" required by the compiler could not be found. Is the reference missing?
You can see this http://www.cnblogs.com/TianFang/archive/2008/08/23/1274678.html.
How the extension method works for me:
In short, for convenience.
C # Extension methods