在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关键字调用父类构造函数时,只能传递参数,无需再次指定参数数据类型,同时须要注意,这些参数的变量名必须与父类构造函数中的参数名一致.若是不同就会出现报错