1. 程式人生 > >C#中子類建構函式

C#中子類建構函式

  在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關鍵字呼叫父類建構函式時,只能傳遞引數,無需再次指定引數資料型別,同時需要注意,這些引數的變數名必須與父類建構函式中的引數名一致.如果不一樣就會出現報錯