親メソッドを作成する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.
}
}
それらを配列に追加します:(私は個人的に a を使用します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)