【问题标题】:Calling a Method from "base.base" class?从“base.base”类调用方法?
【发布时间】:2013-08-19 07:56:37
【问题描述】:

"假设如下代码:

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

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

【问题讨论】:

    标签: c# oop inheritance multiple-inheritance


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这只能使用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关键字hides the inherited member of base class in derived class

      【讨论】:

        【解决方案3】:

        尝试使用“new”关键字代替“override”,并从方法中删除“virtual”关键字;)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-04
          • 2017-11-09
          • 2011-10-24
          • 1970-01-01
          • 2011-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多