擴展方法不僅能擴展具體類別,也能擴展介面。這意味著所有實作該介面的類別都會自動獲得擴展方法,無需逐一修改各類別。
public static void fnIntExtensionMethod()
{
Console.WriteLine("***** Extending an interface *****\n");
MyCalc c = new MyCalc();
Console.WriteLine("1 + 2 = {0}", c.Add(1, 2));
Console.WriteLine("1 - 2 = {0}", c.Subtract(1, 2));
// 也可轉型為介面呼叫擴展方法
Console.WriteLine("30 - 9 = {0}", ((IMath)c).Subtract(30, 9));
// 這行無法編譯:介面無法直接實例化
// IMath itfBM = new IMath();
// itfBM.Subtract(10, 10);
Console.ReadLine();
}
public static class MyExtensionMethods
{
// 擴展 string:轉換為 int
public static int ToInt32(this string s)
{
int i;
Int32.TryParse(s, out i);
return i;
}
// 擴展介面 IMath:提供減法實作
public static int Subtract(this IMath itf, int x, int y)
{
return x - y;
}
}
public interface IMath
{
int Add(int x, int y);
}
class MyCalc : IMath
{
public int Add(int x, int y)
{
return x + y;
}
}
擴展方法定義在靜態類別中,必須 using 該命名空間,否則智能提示不會出現,呼叫也會編譯失敗。
擴展方法在 IntelliSense 中會以向下的藍色箭頭圖示標示,方便與一般實例方法區分。