[英]Constructor of a base class is not inherited in C#
C# 中的構造函數不是繼承的。 必須顯式調用基類的構造函數。 但另一方面,也有人說基類的構造函數在子類構造函數之前被自動調用。
誰能解釋一下?
這取決於你的構造函數是如何實現的,例如
class Human {
public Human() {
Console.WriteLine("I am human");
}
public Human(int i) {
Console.WriteLine("I am human " + i);
}
}
class Man : Human {
public Man() {
Console.WriteLine("I am man");
}
public Man(int i) {
Console.WriteLine("I am man " + i);
}
}
static void Main(string[] args)
{
Man m1 = new Man();
Man m2 = new Man(2);
Console.ReadLine();
}
那么結果將是:
I am human //this is m1
I am man //this is m1
I am human //this is m2
I am man 2 //this is m2
但如果你想要“m2”顯示為
I am human 2 //this is m2
I am man 2 //this is m2
您需要顯式調用基類的構造
class Man : Human {
public Man() {
Console.WriteLine("I am man");
}
public Man(int i) : base(i) {
Console.WriteLine("I am man " + i);
}
}
一個類可以有多個構造函數。 如果一個類是另一個類的子類,那么它的每個構造函數都會調用其基類的構造函數。
如果您在子類構造函數中什么都不做,則在執行子類構造函數的代碼之前,將隱式調用基類的默認(無參數)構造函數。 如果您不想要這種默認行為,您可以選擇要調用的構造函數。
如果我使用@Ivien 的代碼並稍微擴展一下:
public class Human
{
public Human()
{
Console.WriteLine("I am human");
}
public Human(int i)
{
Console.WriteLine("I am human " + i);
}
}
public class Man : Human
{
public Man()
{
Console.WriteLine("I am man");
}
public Man(int i)
{
// The default base class constructor will be implicitly called here
Console.WriteLine("I am man " + i);
}
}
public class Woman : Human
{
public Woman()
{
Console.WriteLine("I am woman");
}
public Woman(int i) : base(i)
{
// I don't want the default base class constructor, so I force a call to the other constructor
Console.WriteLine("I am woman " + i);
}
}
您將看到@Ivien 在他的代碼中看到的相同內容,但您會看到:
I am human 2
I am woman 2
如果你這樣做: var w2 = new Woman(2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.