In C #, we can add extension methods to classes without writing subclasses, as long as the extended class cannot make static classes.
The steps are as follows:
- Defines a static class to contain extension methods. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C # Programming Guide).
- Implement the extension method as a static method and make it at least as visible as the containing class.
- The first parameter of the method specifies the type that the method operates on, which must begin with the this modifier.
- In the calling code, add a using directive to specify the namespace that contains the extension method class.
- The extension method is called in the same way as an instance method on the invocation type.
Note that the first parameter is not specified by the calling code because it represents the type of operator being applied, and the compiler already knows the type of the object. You only need to provide the arguments for these two parameters through N.
Example:
The following example implements an extension method named WordCount in the Customextensions.stringextension class. The method operates on a String class that is specified as the first method parameter. The CustomExtensions namespace is imported into the application namespace, and the method is called within the Main method.
Using System.Linq;
Using System.Text;
Using System;
Namespace CustomExtensions
{
Extension methods must is defined in a static class
public static Class Stringextension
{
This is the extension method.
The first parameter takes the "this" modifier
and specifies the type for which the method is defined.
public static int WordCount (this String str)
{
Return str. Split (new char[] {", '. ', '? '}, Stringsplitoptions.removeemptyentries). Length;
}
}
}
Namespace Extension_methods_simple
{
Import the extension method namespace.
Using CustomExtensions;
Class Program
{
static void Main (string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
Call the method as if it were an
instance method on the type. Note that the first
parameter is isn't specified by the calling code.
int i = S.wordcount ();
System.Console.WriteLine ("Word count of S is {0}", i);
}
}
}
这里方法扩展的关键就是(this 要扩展的类 参数名)这个参数,这个参数也可以不在方法中使用。
如果类的某一方法是由扩展而得,那么在调用的时候,会有相关文字标示。
Reference: http://technet.microsoft.com/zh-cn/bb311042
Custom extension methods in C #