擴充方法讓你不修改原始型別原始碼、不繼承,即可為現有型別「新增」實例方法語法的靜態方法。本質是語法糖,編譯期重寫為靜態方法呼叫。
staticthis 修飾,指定「被擴充的型別」public static class StringExtensions
{
public static int ToInt32(this string s) => Int32.Parse(s);
public static T[] Slice<T>(this T[] source, int index, int count)
{
if (index < 0 || count < 0 || source.Length - index < count)
throw new ArgumentException();
var result = new T[count];
Array.Copy(source, index, result, 0, count);
return result;
}
}
using 指令匯入擴充方法所在的命名空間using Acme.Utilities; // 匯入後 string 即可呼叫 .ToInt32()
using N1;
namespace N1 {
public static class E {
public static void F(this object obj, int i) { }
public static void F(this object obj, string s) { }
}
}
class A { }
class B { public void F(int i) { } }
class C { public void F(object obj) { } }
static void Test(A a, B b, C c) {
a.F(1); // E.F(object, int) - A 無實例方法
a.F("Hello"); // E.F(object, string)
b.F(1); // B.F(int) - 實例方法優先
b.F("Hello"); // E.F(object, string) - B 無 string 多載
c.F(1); // C.F(object) - 實例方法優先(int 隱含轉換 object)
c.F("Hello"); // C.F(object)
}
.Extensions),讓呼叫端明確 usingEnumerable.Where、Select 等)string.IsNullOrWhiteSpace 擴充、DateTime 格式化捷徑)擴充方法是 C# 語法擴充性的關鍵基石,善用它能打造流暢的 DSL 風格 API,但請記住:清晰的架構優於花俏的語法糖。