本文示範如何針對任何 .NET 型別實作您自己的擴充方法。 用戶端程式碼可以使用您的擴充方法。 用戶端專案必須參考包含它們的組件。 用戶端專案必須新增 using 指示詞,以指定會在其中定義擴充方法的命名空間。
定義和呼叫擴充方法:
- 定義靜態類別以包含擴充方法。 這個類別不能巢狀於另一個類型中,而且對用戶端程式碼而言必須是可見的。 如需無障礙規則的詳細資訊,請參閱存取修飾詞。
- 將擴充方法實作為其可見度至少等同於包含類別的靜態方法。
- 方法的第一個參數會指定方法的作業類型,前面必須加上 this 修飾詞。
- 在呼叫程式碼中,新增
using指示詞以指定包含擴充方法類別的命名空間。 - 將方法當做是類型上的執行個體方法進行呼叫。
注意
呼叫程式碼未指定第一個參數,因為它代表要套用運算子的類型,而且編譯器已知物件類型。 您只需要針對參數 2 到 n 提供引數。
下列範例會在 WordCount 類別中實作名為 CustomExtensions.StringExtension 的擴充方法。 此方法會用於指定為第一個方法參數的 String 類別。
CustomExtensions 命名空間會匯入應用程式命名空間,並在 Main 方法內呼叫此方法。
using CustomExtensions;
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 {i}");
namespace CustomExtensions
{
// Extension methods must be defined in a static class.
public static class StringExtension
{
extension(string str)
{
// This is the extension member.
// The `str` parameter is declared on the extension declaration.
public int WordCount()
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
}
多載解析偏好已使用類型自行定義的執行個體或靜態方法,而非擴充方法。 擴充方法無法存取擴充類別中的任何私用資料。