如何實作和呼叫自訂擴充方法 (C# 程式設計手冊)

本主題示範如何針對任何 .NET 類型實作您自己的延伸模組方法。 用戶端程式碼可以使用您的擴充方法,方法是將參考新增至包含這些方法的 DLL,然後新增 using 指示詞,以指定會在其中定義擴充方法的命名空間。

定義和呼叫擴充方法

  1. 定義靜態類別以包含擴充方法。

    此類別對用戶端程式碼而言必須是可見的。 如需存取範圍規則的詳細資訊,請參閱存取修飾詞

  2. 將擴充方法實作為其可見度至少等同於包含類別的靜態方法。

  3. 方法的第一個參數會指定方法的作業類型,前面必須加上 this 修飾詞。

  4. 在呼叫程式碼中,新增 using 指示詞以指定包含擴充方法類別的命名空間

  5. 將方法當做是類型上的執行個體方法進行呼叫。

    請注意,呼叫程式碼未指定第一個參數,因為它代表要套用運算子的類型,而且編譯器已知物件類型。 您只需要針對參數 2 到 n 提供引數。

範例

下列範例會在 CustomExtensions.StringExtension 類別中實作名為 WordCount 的擴充方法。 此方法會用於指定為第一個方法參數的 String 類別。 CustomExtensions 命名空間會匯入應用程式命名空間,並在 Main 方法內呼叫此方法。

namespace CustomExtensions
{
    // Extension methods must be defined in a static class.
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this string str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    // Import the extension method namespace.
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            // Call the method as if it were an
            // instance method on the type. Note that the first
            // parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}

.NET 安全性

擴充方法沒有特定安全性弱點。 它們無法用於模擬類型上的現有方法,因為所有名稱衝突已使用類型自行定義的執行個體或靜態方法解決。 擴充方法無法存取擴充類別中的任何私用資料。

另請參閱