c# - 从 "base.base"类调用方法?

标签 c# oop inheritance multiple-inheritance

“假设以下代码:

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”类上执行方法?我知道我可以执行基本方法(它会打印“我是父亲”),但我想打印“我是祖父”!如果有办法做到这一点,是否在 OOP 设计中推荐?

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

最佳答案

这只能使用 Method Hiding 才能实现-

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关键字在派生类中隐藏基类的继承成员

关于c# - 从 "base.base"类调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281292/

相关文章:

c# - TimeSpan 或 DateTime 作为小时和分钟的参数来解析为 Ticks

javascript - 如何使用 prototype.js 在回调函数中添加参数?

java - 将数据库数据转换为对象

c++ - 已实现类的继承

inheritance - JPA 多重鉴别器值

c# - 读取从ASMX返回的JSON数据

c#线程访问问题

c# - 比较两个对象是否为字符串且是否相等

c++ - 对于可以具有不同状态的结构,我应该使用哪种设计模式?

c++ - 从递归模板类继承