[英]Correct way to invoke constructor of a parent class from the child
我有一个继承自另一个的班级; 父类具有所有统计数据(想象一个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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.