C # can be defined
Extension Method , You can also
Extension Method for the set .
Example:
Extension Method
Using System;
Using System. Collections. Generic;
Using MySpace; // Note: space for introducing extension methods
Namespace Con_1
{
Class Program
{
Static Void Main ( String [] ARGs)
{
String Str = " Mr. {0. " . ( " Xugang " );
Console. writeline ( " Hello! " + Str );
//2 call the extension method of the Set
Str. showitems<Char>();
}
}
}
Namespace MySpace
{
// Extension methods must be defined in non-generic static classes.
Public Static Class Mymethods
{
// Note: The first parameter uses "this" to obtain the current object.
Public Static String With ( This String _ Context, Params String [] _ ARGs)
{
Return String . Format (_ context, _ ARGs );
}
// 2. Perform expansion for the set
Public Static Void Showitems < T > ( This Ienumerable < T > _ Al)
{
Foreach (VAR item In _ Al)
{
Console. writeline (item );
}
}
}
}
Note:
1 C # Only extension methods are supported, and extended attributes and events are not supported;
2. There is no limit to the method name. The first parameter must contain this;
3. namespace system can be used for the namespace of the extension method, but it is not recommended;
4. The class defining the extension method is a static class;
After the method is extended by using this parameterProgram During compilation, the Assembly will add something similar to the following on the corresponding static class. This makes it easy to find a call. [Attributeusage (attributetargets. Method | Attributetargets. Class | Attributetargets. Assembly)]
Public Sealed Class Extensionattribute: attribute
{
......
}
In msil, the followingCode : . Custom instance Void [System. Core] system. runtime. compilerservices. extensionattribute:. ctor () = ( 01 00 00 00 ) We can see that system. Core. dll must be referenced during runtime.
Reference Source:
C # extension methods under advanced methods
C # features-Extension Method
C # amazing use of extension methods