Extension會有以下這些特徵:
- 必須在非generic的static class中,並且宣告為static method
- Method最少要有一個參數
- 第一個參數用this關鍵字宣告
- 第一個參數不能有this以外的修飾詞,例如out或ref
- 第一個參數型態不能是pointer type
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,我們可以這樣使用它:Console.WriteLine("Test".IsCapitalized());
其實這段呼叫在編譯時候會被修改成去呼叫static method,背後的細節被compiler隱藏起來。Console.WriteLine(StringHelper.IsCapitalized("Test"));
總結一下,extension method背後會做以下轉換:arg0.Method(arg1, arg2, ...); // Extension method call StaticClass.Method(arg0, arg1, arg2, ...); // Static method callInterface也可以被extended,範例如下:
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
沒有留言:
張貼留言