1.觀察兩個類
class A
{
protected int i = 0;
public A()
{
i = 1;
}
public void P()
{
System.Console.WriteLine("P:"+i.ToString());
}
public virtual void VP()
{
System.Console.WriteLine("VP in A:" + i.ToString());
}
}
class B:A
{
public B()
{
i = 2;
}
public B(int i)// public B(int i) = public B(int i):base()
{
//this.i = i;
//keep this section as empty, while the base constructor will be invoked
}
public override void VP()
{
System.Console.WriteLine("VP in B:" + i.ToString());
//base.VP();
}
}
2.
A b = new A();
b.P();
b.VP();
Console.Read();
//調用預設建構函式
//調用虛方法
//一切都很簡單而且美好
A b1 = new B();
b1.P();
b1.VP();
//調用衍生類別的建構函式 ,
//衍生類別的建構函式調用基類的預設建構函式
A b2 = new B(0);
b1.P();
b1.VP();
//調用衍生類別中帶參數的建構函式時 public B(int i) = public B(int i):base()
//先調用衍生類別的建構函式
//衍生類別的建構函式調用基類的預設建構函式
// 有呼叫堆疊為證
//> ConsoleApplication2.exe!ConsoleApplication2.A.A() 行 11 C#
// ConsoleApplication2.exe!ConsoleApplication2.B.B() 行 30 + 0x8 位元組 C#
// ConsoleApplication2.exe!ConsoleApplication2.Program.Main(string[] args = {string[0]}) 行 64 + 0x15 位元組 C#
結論:
1建構函式無法用virtual和override修飾,會造成編譯錯誤
2父建構函式可以被修改,但不是重寫,也不是重載,而是在調用時注入了新函數的代碼
3在同一繼承層次的同一個類中,建構函式可以重載