C# Extension Method功能解析
C#3.0之后提供extension method这个功能,简单来说就是让你在现有的type中加入新的的method。一般是用在内建型态或是sealed class上,一般的type我们可以通过继承的方式来加入新method,但是我们没办法修改内建型态,因此extension method就派上用场了。
Extension会有以下这些特徵:
1、必须在非generic的static class中,并且宣告为static method
2、Method最少要有一个参数
3、第一个参数用this关键字宣告
4、第一个参数不能有this以外的修饰词,例如out或ref
5、第一个参数型态不能是pointer type
以下是一个extension method的范例
view plaincopy to clipboardprint?
public static class StringHelper
{
public static bool IsCapitalized (this string s)
{
if (string.IsNullOrEmpty(s)) return false;
return char.IsUpper(s[0]);
}
}
IsCapitalized就是string type的extension method,我们可以这样使用它:
view plaincopy to clipboardprint?
Console.WriteLine("Test".IsCapitalized());
其实这段呼叫在编译时候会被修改成去呼叫static method,背后的细节被compiler隐藏起来。
view plaincopy to clipboardprint?
Console.WriteLine(StringHelper.IsCapitalized("Test"));
总结一下,extension method背后会做以下转换:
view plaincopy to clipboardprint?
arg0.Method(arg1, arg2, ...); // Extension method call
StaticClass.Method(arg0, arg1, arg2, ...); // Static method call
Interface也可以被extended,范例如下:
view plaincopy to clipboardprint?
public static T First
(this IEnumerable sequence) {
foreach (T element in sequence)
return element;
throw new InvalidOperationException("No elements!");
}
...
Console.WriteLine("Test".First()); // Output: T
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
