Calling a Method from "base.base" class?

本文关键字:base quot class Method from Calling | 更新日期: 2023-09-27 18:28:01

"假设以下代码:

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");
    }
}

我想从"孩子"对象打印"我是爷爷"。

如何让Child对象在"base.base"类上执行方法?我知道我可以执行基本方法(它会打印"I Am a Father"),但我想打印"I Am a GrandFather"!如果有办法做到这一点,在OOP设计中推荐吗?

注意:我不使用/将使用这种方法,我只是想加强知识继承。

Calling a Method from "base.base" class?

这只能使用方法隐藏-实现

public class GrandFather
{
    public virtual void WhoAreYou()
    {
        Console.WriteLine("I am a GrandFather");
    }
}
public class Father : GrandFather
{
    public new void WhoAreYou()
    {
        Console.WriteLine("I am a Father");
    }
}
public class Child : Father
{
    public new void WhoAreYou()
    {
        Console.WriteLine("I am a Child");            
    }
}

这样称呼它-

Child child = new Child();
((GrandFather)child).WhoAreYou();

使用new关键字hides the inherited member of base class in derived class

尝试使用"new"关键字而不是"override",并从方法中删除"virtual"关键字;)

此程序在运行时出错。确保子对象将引用父类,然后使用引用类型强制转换调用方法例如:child-child=新爷爷()/这里我们正在创建引用parentclass的child实例/((爷爷)孩子)WhoAreYou();/*现在我们可以使用引用类型*/否则,它们在祖父类型铸造下显示错误。