[英]Initialize base class’s fields in subclass constructor in C#
我有一个带有三个字段的基类,但是没有像这样正常的方式初始化它的字段:
class ParentClass
{
public string Name { get; set; }
public string Family { get; set; }
public string Address { get; set; }
public ParentClass(string Name, string Family, string Address)
{
this.Name = Name;
this.Family = Family;
this.Address = Address;
}
}
class ChildClass : ParentClass
{
public int StudentID { get; set; }
public int StudentScore { get; set; }
public ChildClass(string Name, string Family, string Address, int StudentID, int StudentScore)
: base(Name, Family, Address)
{
this.StudentID = StudentID;
this.StudentScore = StudentScore;
}
static void Main(string[] args)
{
var Pro = new ChildClass("John", "Greene", "45 Street", 76, 25);
Console.WriteLine(Pro.Name + Pro.Family + Pro.Address + Pro.StudentID + Pro.StudentScore);
}
}
我已经初始化了ChildClass构造函数中的字段,而没有像这样显式调用基类构造函数:
class ParentClass
{
public string Name { get; set; }
public string Family { get; set; }
public string Address { get; set; }
}
class ChildClass : ParentClass
{
public int StudentID { get; set; }
public int StudentScore { get; set; }
public ChildClass(int StudentID, int StudentScore)
{
Name = "John";
Family = "Greene";
Address = "45 Street";
this.StudentID = StudentID;
this.StudentScore = StudentScore;
}
static void Main(string[] args)
{
var Pro = new ChildClass(76, 25);
Console.WriteLine(Pro.Name + Pro.Family + Pro.Address + Pro.StudentID + Pro.StudentScore);
}
}
我知道我可以在父类本身中初始化父类的字段,这是一个虚假的示例,但是我想知道在现实生活和更复杂的情况下执行类似的操作是否被认为是一种好的做法?为什么我不应该做这样的事情? 不显式调用基类构造函数?
编辑:我更担心没有显式调用基类构造函数并在子类部分对其进行初始化,因此我编辑了最后一部分,提到了暴露出来的字段。
如您所见,这些字段已经 “公开”。 在第一个示例中,您仍然可以从派生类中获取这些变量。
至于不使用基类构造函数是一种好习惯,我会说不。 通过仅具有参数化的基类构造函数,您可以确保该类的将来的实现者初始化基类属性。 例如,您可以在第二秒钟写:
public ChildClass(int StudentID, int StudentScore)
{
this.StudentID = StudentID;
this.StudentScore = StudentScore;
}
没有错误。 除此之外,您的样本之间几乎没有差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.