讓我們假設我們有下面的代碼:基本方法是否能夠使用派生的基礎數據成員?
abstract class Base1 {
protected int num;
}
class Der1:Base1 {
protected Color color;
protected string name;
}
class Der2:Base1 {
protected DateTime dthen;
}
等。存在一個base1
類型的數組,其中包含許多由派生自base1
的類創建的對象。
是否可以僅在基類中定義toString()
方法? 類似:
public override string toString()
{
if (this is Der1)
return "num = " + this.num + "color = " + this.color.toString() + " name = " this.name;
if (this is Der2)
return "num = " + this.num + "dthen = " + this.dthen.toString();
// and so on ...
}
非常感謝你:)
附:這不是一個家庭作業問題。我只是想知道。
+1讓CLR處理多態調度 - 它更乾淨,更快,更容易維護。 – 2010-03-17 13:34:49
不,「((Der1)this).color'是一個編譯錯誤,即使在Base1類中也是如此。 – 2010-03-17 13:35:02
@Anton:我已經編輯過。 – SLaks 2010-03-17 13:36:06