[英]Inadvertent base class constructor “hiding” in derived class
[注意:編寫的代碼僅用於顯示問題,而不是因為它本身有用。]
假設我有兩個類, A
和B
:
public class A {
public const int max = 2;
public int[] id;
public A() {
this.id = new int[A.max];
}
public A(int id) : this() {
this.id[0] = id;
}
public A(int id, int id2) : this() {
this.id[0] = id;
this.id[1] = id2;
}
}
public class B : A {
public B(int[] ids) : base() {
int x = 0;
while ( ( x < ids.Length ) && ( x < A.max ) ) {
this.id[x] = ids[x];
x++;
}
}
}
似乎通過在B
創建新的構造函數,我無意中隱藏了所有通常由B
從A
“繼承”的構造函數(實際上,我已經知道構造函數不是在C#中繼承的,但我是仍然困惑在這里)。
例如:
A first = new A(); // fine
int[] x = new int[A.max-1];
B second = new B(x); // fine
B third = new B(12); // nope
如果我從B
刪除新的構造函數,那么B third = new B(12);
工作得很好(在我的術語中,構造函數不再“隱藏”)。 但是使用B
的新構造函數,我不能再使用A(int)
構造函數了。
那么解決方案真的只是重新定義我希望B從A繼承並使它們為空的所有構造函數嗎? 例:
public class B : A {
public B(int id) : base(id) {} // adding this!
public B(int[] ids) : base() {
int x = 0;
while ( ( x < ids.Length ) && ( x < A.max ) ) {
this.id[x] = ids[x];
}
}
}
如果我做出改變,現在B third = new B(12);
工作得很好。 但是我必須重新定義我想在派生類的基類中使用的每個構造函數,這似乎有點難看,因為我正在為該派生類添加一個新的構造函數!
是的,派生類不會從基類中獲取或公開構造函數。 您需要在基類中定義所有必需的構造函數(可能調用基類的構造函數)。
注意:如果派生類沒有任何內容可以初始化,您可能需要重新考慮是否真的需要新類。
我認為你是絕對正確的EleventyOne你的例子很笨重,但問題不在於它是你設計的語言。 我知道你的例子不是一個現實世界的例子,因此抽象的問題會產生抽象的答案。
如果你發現自己的基類很多構造函數,你的設計是錯誤的。 您可能正在嘗試在繼承中建模更適合組合的東西,或者您的基類應該接受對象而不是單個相關屬性,如果屬性不相關那么可能您的基類做得太多(單一責任)原理)。
當它感覺不對時,你有一個代碼味道! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.