从子类调用父类构造函数的正确方法
本文关键字:方法 构造函数 子类 调用 父类 | 更新日期: 2023-09-27 18:34:51
我有一个从另一个类继承的类;父类具有所有统计信息(想象一个RPG角色表(,而子类只有几个额外的参数。
当我启动子类时,如何调用父类的构造函数,以使用泛型数据初始化所有参数?我必须显式调用它还是 C# 自动调用它?
父类:
public class genericguy
{
private string _name;
private int _age;
private string _phone;
public genericguy(string name)
{
this._name = name;
this._age = 18;
this._phone = "123-456-7890";
}
// the rest of the class....
}
儿童班:
public class specificguy:genericguy
{
private string _job;
private string _address;
public specificguy(string name)
{
this._name = name;
this._job = "unemployed";
this._address = "somewhere over the rainbow";
// init also the parent parameters, like age and phone
}
// the rest of the class....
}
在这个例子中,我有 genericguy 类;它有 3 个参数,在构造函数中创建对象时设置这些参数。我想在名为"specificguy"的子类中,这些参数已初始化,就像在父级中发生的那样。如何正确执行此操作?在Python中,你总是调用父("__init__")
的构造函数,但我不确定C#
儿童类:
public class specificguy:genericguy
{
private string _job;
private string _address;
//call the base class constructor by using : base()
public specificguy(string name):base(name) //initializes name,age,phone
{
//need not initialize name as it will be initialized in parent
//this._name = name;
this._job = "unemployed";
this._address = "somewhere over the rainbow";
}
}
答案有两个部分:
- 通过使用
: base(...)
语法调用基构造函数 - 不要在派生类中重复基类所做的赋值。
如果是您的specificguy
则意味着构造函数应如下所示:
public specificguy(string name) : base(name)
{
// The line where you did "this._name = name;" need to be removed,
// because "base(name)" does it for you now.
this._job = "unemployed";
this._address = "somewhere over the rainbow";
// init also the parent parameters, like age and phone
}
在 Python 中,你总是调用父构造函数
("__init__")
C# 将自动为您调用无参数构造函数;如果缺少此类构造函数,则必须通过: base(...)
语法提供显式调用。
您可以将子类构造函数声明为
public specificguy(string name) : base(name)