1

“假设以下代码:

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 设计中是否推荐?

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

4

3 回答 3

5

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

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.

于 2013-08-16T20:11:55.940 回答
2

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

于 2013-08-16T20:10:27.067 回答
0

该程序在您运行时会出错。确保 child 的对象将引用父类,然后使用引用类型转换调用方法 例如:child child = new grandparent();/这里我们正在创建引用父类的 child 的实例。/ (((Grandfather)child).WhoAreYou();/* 现在我们可以使用引用类型*/ 否则它们会在祖父类型转换下显示错误。

于 2017-01-10T06:19:58.810 回答