擴充方法允許在不修改原型別原始碼、不繼承的情況下,為現有型別「新增」實例方法語法。本質是靜態方法的語法糖,編譯期轉換為靜態呼叫。廣泛用於 LINQ (Enumerable)、框架擴充、DSL 建構。
public static class StringExtensions
{
// this 修飾第一個參數 → 擴充方法
public static bool IsNullOrEmpty(this string str) => string.IsNullOrEmpty(str);
public static string TrimTo(this string str, int maxLen) => str?.Length > maxLen ? str.Substring(0, maxLen) : str;
}
static、非巢狀、非泛型 (但方法可為泛型)。static。this,型別即為擴充目標。using 才生效。
string s = "hello";
bool b = s.IsNullOrEmpty(); // 實例語法
bool b2 = StringExtensions.IsNullOrEmpty(s); // 靜態語法,等價
IEnumerable.Where)。public static TResult Map(this TSource src, Func selector) this 或建構器物件,建構 DSL。using MyExtensions; 會將擴充方法注入所有型別 IntelliSense,造成雜訊。建議將擴充方法放在獨立命名空間,按需引用。object、string、IEnumerable 等高層型別影響極大,嚴謹評估必要性。AddRange)。