在C#中,一個子類繼承父類后,兩者的構造函數又有何關系??
1.隱式調用父類構造函數
----------------父類
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 }
----------------------子類
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函數中調用
static void Main(string[] args) { SE se = new SE("112","張三",25,Gender.male,100); Console.WriteLine(se.SayHi()); Console.ReadLine(); }
-----------------運行結果
由上可知
創建子類對象時會首先調用父類的構造函數,然后才會調用子類本身的構造函數.
如果沒有指明要調用父類的哪一個構造函數,系統會隱式地調用父類的無參構造函數
2.顯式調用父類構造函數
C#中可以用base關鍵字調用父類的構造函數.只要在子類的構造函數后添加":base(參數列表)",就可以指定該子類的構造函數調用父類的哪一個構造函數.
這樣可以實現繼承屬性的初始化,然后在子類本身的構造函數中完成對子類特有屬性的初始化即可.
------------------子類代碼變更為其余不變
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關鍵字調用父類構造函數時,只能傳遞參數,無需再次指定參數數據類型,同時需要注意,這些參數的變量名必須與父類構造函數中的參數名一致.如果不一樣就會出現報錯