[英]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.