首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 事件深度解析(五):建構函式鏈結、解構函式與靜態建構函式執行順序

     編輯:關於C語言

可選參數的建構函式鏈結

透過 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

執行順序取決於執行引擎,不可假設固定順序。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved