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

C# 事件深度解析(三):建構函式初始化器、基底/本類別鏈結與自動插入機制

     編輯:關於C語言

實例變數初始化器與建構函式初始化器

若建構函式無初始化器或為 base(...),編譯器會隱含執行類別宣告順序的實例欄位初始化器,緊接著隱式呼叫基底建構函式。此序列相當於自動插入在建構函式主體第一行之前。

完整範例與自動展開對照

using System.Collections;
class A
{
    int x = 1, y = -1, count;
    public A() { count = 0; }
    public A(int n) { count = n; }
}
class B : A
{
    double sqrt2 = Math.Sqrt(2.0);
    ArrayList items = new ArrayList(100);
    int max;
    public B() : this(100) { items.Add("default"); }
    public B(int n) : base(n - 1) { max = n; }
}

編譯器自動展開後等效於:

class A
{
    int x, y, count;
    public A() { x = 1; y = -1; object(); count = 0; }
    public A(int n) { x = 1; y = -1; object(); count = n; }
}
class B : A
{
    double sqrt2; ArrayList items; int max;
    public B() : this(100) { B(100); items.Add("default"); }
    public B(int n) : base(n - 1) { sqrt2 = Math.Sqrt(2.0); items = new ArrayList(100); A(n - 1); max = n; }
}

註解標示自動插入語句:欄位初始化、基底建構函式呼叫、this(...) 鏈結呼叫。注意 base 與 this 不能同時出現。

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