若建構函式無初始化器或為 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 不能同時出現。