void 都不能寫)。private 建構函式可防止外部實例化 (單例、工廠模式)。class Point
{
public int X, Y;
public Point() : this(0, 0) { } // 呼叫雙參數版
public Point(int x) : this(x, 0) { } // 呼叫雙參數版
public Point(int x, int y) { X = x; Y = y; } // 真正初始化邏輯
}
this(...) 必須是建構函式第一條語句。class Config
{
public static string ConnectionString;
static Config() // 無修飾詞、無參數、自動在第一次存取靜態成員/建立實例前執行一次
{
ConnectionString = LoadFromConfigFile();
}
}
class ResourceHolder : IDisposable
{
private IntPtr _handle;
~ResourceHolder() // 語法: ~ClassName(),編譯為 Finalize()
{
Dispose(false);
}
// ... IDisposable 實作
}
IDisposable 模式。delete/RAII 不同)。class Base { public Base() => Console.WriteLine("Base()"); }
class Derived : Base { public Derived() => Console.WriteLine("Derived()"); }
// new Derived() 輸出:
// Base()
// Derived()
base())。base(...) 顯式指定。class Base
{
public Base() { }
public Base(int x) { }
public Base(string s1, string s2) { }
}
class D1 : Base { public D1() : base() { } } // 明確呼叫無參
class D2 : Base { public D2() : base(123) { } } // 呼叫 int 版
class D3 : Base { public D3() : base("a", "b") { } } // 呼叫 string 版
| 情境 | 範例 | 說明 |
|---|---|---|
| 限定同名欄位/參數 | this.name = name; | 區分欄位 name 與參數 name |
| 建構函式鏈結 | public C() : this(0) { } | 呼叫同類別其他建構函式 |
| 索引子宣告 | public int this[int i] { get; } | 定義索引子 |
| 傳遞當前實例 | Other.Method(this); | 作為引數傳遞 |
| 比較實例身分 | if (this == other) ... | 參考比較 |
| 擴充方法接收者 | public static void Ext(this MyClass c) { } | 定義擴充方法 (static 類別中) |
abstract class Shape
{
protected int _id;
protected Shape(int id) => _id = id; // 受保護建構函式
public int Id => _id;
}
class Rectangle : Shape
{
public int Width { get; }
public int Height { get; }
// 完整建構函式
public Rectangle(int id, int w, int h) : base(id)
{
Width = w; Height = h;
}
// 便利建構函式鏈結
public Rectangle(int w, int h) : this(0, w, h) { }
public Rectangle() : this(10, 10) { } // 預設 10x10
}
new Widget(new Options { ... }))。struct 不能有無參建構函式 (CLR 預設零值初始化),自訂建構函式必須初始化所有欄位。建構函式是物件生命週期的起點。善用 this() 鏈結消除重複、base() 正確初始化基類、static 建構函式處理靜態狀態、IDisposable 取代解構函式管理資源,能寫出正確、清晰、可維護的初始化邏輯。