在C#中,一個子類繼承父類後,二者的構造函數又有何關係??函數
1.隱式調用父類構造函數this
----------------父類spa
1 public class Employee 2 { 3 public Employee(){ 4 Console.WriteLine("父類無參對象構造執行!"); 5 } 6 public Employee(string id, string name, int age, Gender gender) 7 { 8 this.Age = age; 9 this.Gender = gender; 10 this.ID = id; 11 this.Name = name; 12 } 13 protected string ID { get; set; } //工號 14 protected int Age { get; set; } //年齡 15 protected string Name { get; set; } //姓名 16 protected Gender Gender { get; set; } //性別 17 }
----------------------子類code
public class SE : Employee { public SE() { } //子類 public SE(string id, string name, int age, Gender gender, int popularity) { this.Age = age; this.Gender = gender; this.ID = id; this.Name = name; this.Popularity = popularity; } private int _popularity; //人氣 public string SayHi() { string message; message = string.Format("你們好,我是{0},今年{1}歲,工號是{2},個人人氣值高達{3}!", base.Name, base.Age, base.ID, this.Popularity); return message; } public int Popularity { get { return _popularity; } set { _popularity = value; } } }
--------------------Main函數中調用orm
static void Main(string[] args) { SE se = new SE("112","張三",25,Gender.male,100); Console.WriteLine(se.SayHi()); Console.ReadLine(); }
-----------------運行結果對象
由上可知blog
建立子類對象時會首先調用父類的構造函數,而後纔會調用子類自己的構造函數.
若是沒有指明要調用父類的哪個構造函數,系統會隱式地調用父類的無參構造函數繼承
2.顯式調用父類構造函數get
C#中能夠用base關鍵字調用父類的構造函數.只要在子類的構造函數後添加":base(參數列表)",就能夠指定該子類的構造函數調用父類的哪個構造函數.
這樣能夠實現繼承屬性的初始化,而後在子類自己的構造函數中完成對子類特有屬性的初始化便可.string
------------------子類代碼變動爲其他不變
public class SE : Employee { public SE() { } //子類 public SE(string id, string name, int age, Gender gender, int popularity):base(id,name,age,gender) { //繼承自父類的屬性 //調用父類的構造函數能夠替換掉的代碼 //this.Age = age; //this.Gender = gender; //this.ID = id; //this.Name = name; this.Popularity = popularity; } private int _popularity; //人氣 public string SayHi() { string message; message = string.Format("你們好,我是{0},今年{1}歲,工號是{2},個人人氣值高達{3}!", base.Name, base.Age, base.ID, this.Popularity); return message; } public int Popularity { get { return _popularity; } set { _popularity = value; } } }
運行結果爲
注意:base關鍵字調用父類構造函數時,只能傳遞參數,無需再次指定參數數據類型,同時須要注意,這些參數的變量名必須與父類構造函數中的參數名一致.若是不同就會出現報錯