撰寫多載建構函式時,切勿複製貼上或抽取私有輔助方法。C# 提供建構函式初始化運算式(this(...) / base(...)),讓一個建構函式委派另一個,避免程式碼重複,且編譯器會最佳化:移除重複欄位初始化與基類建構呼叫,產生最高效 IL。
public class MyClass
{
private ArrayList _coll;
private string _name;
public MyClass() : this(0, "") { }
public MyClass(int initialCount) : this(initialCount, "") { }
public MyClass(int initialCount, string name)
{
_coll = (initialCount > 0) ? new ArrayList(initialCount) : new ArrayList();
_name = name;
}
}
輔助方法版本:
public MyClass() { CommonConstructor(0, ""); }
public MyClass(int count) { CommonConstructor(count, ""); }
private void CommonConstructor(int count, string name) { ... }
編譯器會在每個建構函式插入:欄位預設初始化(置零)、基類建構呼叫、再呼叫輔助方法。建構函式鏈結版本:只有最完整的建構函式執行欄位初始化與基類呼叫,其餘僅委派,零重複指令。
readonly 欄位只能在建構函式中指派。輔助方法無法指派 readonly 欄位(編譯錯誤),建構函式鏈結則完全支援。
後續實例從第 5 步開始。第 6、7 步經編譯器最佳化(建構函式鏈結時移除重複)。
this(...)),避免重複程式碼與 IL 指令。