擴展方法允許開發者在不修改原始型別、不繼承、不重新編譯的情況下,為現有型別(包括介面、實值型別、參考型別)新增方法。這類似於裝飾器模式,但語法更直觀,使用起來如同實例方法一般自然。
關鍵在於靜態類別中的靜態方法,第一個參數前加上 this 修飾詞:
public static class StringExtensions
{
// 將下底線命名轉為駝峰式命名
public static string ToCamelCase(this string identifier)
{
string result = "";
bool sawUnderscore = false;
foreach (char c in identifier)
{
if (result.Length == 0 && char.IsLetter(c))
result += char.ToUpper(c);
else if (c == '_')
sawUnderscore = true;
else if (sawUnderscore)
{
result += char.ToUpper(c);
sawUnderscore = false;
}
else
result += c;
}
return result;
}
}
// 使用方式:像呼叫實例方法一樣
string[] identifiers = { "do_something", "find_all_objects", "get_last_dict_entry" };
foreach (string s in identifiers)
Console.WriteLine("{0} becomes: {1}", s, s.ToCamelCase());
原本需呼叫 StringExtensions.ToCamelCase(s),現在直接寫 s.ToCamelCase(),程式碼更符合物件導向直覺。
public static class ListExtensions
{
public static List<T> Combine<T>(this List<T> first, List<T> second)
{
var combined = new List<T>(first);
combined.AddRange(second);
return combined;
}
}
// 使用範例
var odds = new List<int> { 1, 3, 5, 7 };
var evens = new List<int> { 0, 2, 4, 6 };
var all = odds.Combine(evens); // { 1, 3, 5, 7, 0, 2, 4, 6 }
擴展方法是 LINQ 查詢運算子(Where、Select、OrderBy 等)的基石,也是 C# 實現「開放封閉原則」的重要手段之一。