1. 程式人生 > >c#建構函式中的this和base

c#建構函式中的this和base

首先要明確this指向的本例項的建構函式,base指向的時基類的建構函式。

再執行順序上a、this表明,在執行本建構函式之前,先執行this指向本例項的建構函式,再執行本函式。

                        b、base表明,在執行本建構函式之前,先執行base指向的基類的建構函式,再執行本函式。

示例demo:

建立兩個 類,一個 One(基類),Two(繼承自One)。

using System;
namespace cSharp { class Program { static void Main( string[] args) { One oneObj = new One(); Console. WriteLine( "---------------------------------"); Two
twoObj = new Two(); Console. ReadKey(); } } class One {
public string Name{ set; get;} public int Age{ get; set; } public bool Sex{ get; set;}
public One( string
name, int age, bool sex) { Console. WriteLine( "One 呼叫帶引數建構函式"); this. Name = name; this. Age = age; this. Sex = sex; }
public One(): this( "預設姓名", 18, true) //在呼叫之前首先 呼叫本例項的 有引數 的建構函式,再執行本建構函式 { Console. WriteLine( "One 呼叫不帶引數建構函式"); }
}
class Two: One { public string Like{ get; set;}
public Two() : base() //在呼叫之前 先呼叫 基類的 無引數 建構函式,再執行本建構函式 { Console. WriteLine( "two 無引數"); }
public Two( string like): this() //在呼叫之前先呼叫 本例項的 無引數的建構函式 。即Two(),再執行本建構函式 { this. Like = like; } }
}

執行結果: