共用方式為


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

本主題將說明如何實作您自己的擴充方法中的任何型別的。NET Framework 類別庫,或其他。您想要擴充的 NET 型別。 用戶端程式碼可以使用您的擴充方法,方法是將參考加入至包含擴充方法的 DLL,以及加入 using 指示詞,該指示詞指定在其中定義擴充方法的命名空間。

若要定義及呼叫擴充方法

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

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

  2. 以至少與包含類別相同的可視性,將擴充方法實作為靜態方法。

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

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

  5. 呼叫方法,如同它們是型別上的執行個體方法一般。

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

範例

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

using System.Linq;
using System.Text;
using System;

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

編譯程式碼

若要執行這個程式碼,請將它複製並貼上至在 Visual Studio 中所建立的 Visual C# 主控台應用程式專案。 根據預設,這個專案是以 .NET Framework 3.5 版為目標,而且有 System.Core.dll 的參考,以及 System.Linq 的 using 指示詞。 如果專案中缺少一個或多個要求,您可以手動加入。 如需詳細資訊,請參閱 如何:建立 LINQ 專案

安全性

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

請參閱

參考

擴充方法 (C# 程式設計手冊)

靜態類別和靜態類別成員 (C# 程式設計手冊)

protected (C# 參考)

internal (C# 參考)

public (C# 參考)

this (C# 參考)

namespace (C# 參考)

概念

C# 程式設計手冊

其他資源

LINQ (Language-Integrated Query)