“假设以下代码:
public class MultiplasHerancas
{
static GrandFather grandFather = new GrandFather();
static Father father = new Father();
static Child child = new Child();
public static void Test()
{
grandFather.WhoAreYou();
father.WhoAreYou();
child.WhoAreYou();
GrandFather anotherGrandFather = (GrandFather)child;
anotherGrandFather.WhoAreYou(); // Writes "I am a child"
}
}
public class GrandFather
{
public virtual void WhoAreYou()
{
Console.WriteLine("I am a GrandFather");
}
}
public class Father: GrandFather
{
public override void WhoAreYou()
{
Console.WriteLine("I am a Father");
}
}
public class Child : Father
{
public override void WhoAreYou()
{
Console.WriteLine("I am a Child");
}
}
我想从“孩子”对象打印“我是祖父”。
我如何让子对象在“base.base”类上执行方法?我知道我可以执行基本方法(它会打印“我是父亲”),但我想打印“我是祖父”!如果有办法做到这一点,在 OOP 设计中是否推荐?
注意:我不使用/将使用这种方法,我只是想加强知识继承。