首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 3.0 系列:擴展方法 (3) — 擴展介面類型

     編輯:關於C語言

擴展介面:為所有實作類別統一新增功能

擴展方法不僅能擴展具體類別,也能擴展介面。這意味著所有實作該介面的類別都會自動獲得擴展方法,無需逐一修改各類別。

程式碼範例

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;
    }
}

關鍵觀念

  • 擴展介面時必須提供方法實作,不像介面宣告僅有簽章。
  • 無法直接在介面實例上呼叫(介面無法實例化),只能透過實作類別的實例,或將實例轉型為介面型別後呼叫。
  • 語意上可理解為:所有實作該介面的物件都新增了這些擴展功能。

使用注意事項

1. 必須引用命名空間

擴展方法定義在靜態類別中,必須 using 該命名空間,否則智能提示不會出現,呼叫也會編譯失敗。

2. Visual Studio 智能提示標識

擴展方法在 IntelliSense 中會以向下的藍色箭頭圖示標示,方便與一般實例方法區分。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved