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关键字调用父类构造函数时,只能传递参数,无需再次指定参数数据类型,同时需要注意,这些参数的变量名必须与父类构造函数中的参数名一致.如果不一样就会出现报错
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)