【发布时间】:2015-03-30 13:31:53
【问题描述】:
我有一个包含三个字段的基类,但不是像这样以正常方式初始化它的字段:
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);
}
}
我知道我可以在父类本身中初始化父类的字段,这是一个虚假的例子,但我想知道在现实生活和更复杂的情况下做类似的事情是否被认为是一种好习惯,是我有什么理由不应该做这样的事情?至于不显式调用基类构造函数?
编辑:我更担心没有显式调用基类构造函数并在子类部分初始化它,所以我编辑了最后提到的字段被暴露出来的部分。 p>
【问题讨论】:
-
如果您想访问或使用
chieldClass中的parentClass字段,您必须将它们暴露给chieldClass即:通过使它们成为protected或public,那么是什么问题?我认为您的问题完全没有意义,根本没有用!!!!!!! -
我比较担心没有显式调用基类构造函数部分,你没注意,我把最后一部分编辑掉了,以免造成更多混乱。
标签: c# constructor subclass base-class