透過 this(...) 串聯建構函式,為缺少參數提供預設值:
class Text
{
public Text() : this(0, 0, null) { }
public Text(int x, int y) : this(x, y, null) { }
public Text(int x, int y, string s) { /* 真正初始化 */ }
}
// 使用
Text t1 = new Text(); // 等同 Text(0, 0, null)
Text t2 = new Text(5, 10); // 等同 Text(5, 10, null)
Text t3 = new Text(5, 20, "Hello");
實作物件銷毀行為,命名必須與類別相同(前綴 ~),無參數、無回傳值:
class MyClass
{
~MyClass() { /* 清理非受控資源 */ }
}
靜態建構函式在第一次存取類別前自動執行,但多類別間順序不保證:
class A { static A() { Console.WriteLine("Init A"); } public static void F() { Console.WriteLine("A.F"); } }
class B { static B() { Console.WriteLine("Init B"); } public static void F() { Console.WriteLine("B.F"); } }
// 可能輸出:
// Init A / A.F / Init B / B.F
// 或
// Init B / Init A / A.F / B.F
執行順序取決於執行引擎,不可假設固定順序。