我有一个继承自另一个人的班级;父类具有所有统计数据(想象一个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#
答案 0 :(得分:2)
儿童班:
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";
}
}
答案 1 :(得分:1)
答案分为两部分:
: 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(...)
语法提供显式调用。
答案 2 :(得分:0)
您可以将子类构造函数声明为
GETUTCDATE()