如果您使父級方法virtual
您可以重寫您的子類中的基本方法。
public class Human
{
// Virtual method
public virtual void Say()
{
Console.WriteLine("i am a human");
}
}
public class Male: Human
{
// Override the virtual method
public override void Say()
{
Console.WriteLine("i am a male");
base.Draw(); // --> This will access the Say() method from the
//parent class.
}
}
它們添加到陣列:(本書雖然是我個人使用List<T>
)
Human[] x = new Human[2];
x[0] = new Human();
x[1] = new Male();
打印出結果:
foreach (var i in x)
{
i.Say();
}
會打印出
"i am a human" // --> (parent class implementation)
"i am a male" // --> (child class implementation)
有你嘗試了'virtual'和'override'鍵話?你有什麼嘗試?顯示類的代碼,以便我們可以看到導致行爲的原因。 – zimdanen
如果您將對象創建爲父對象,則只能訪問父對象中的屬性/方法。您需要將該對象創建爲子對象以調用子方法。 – landoncz
你能發表一些代碼嗎? –