【问题标题】:multilevel inheritance with same method names c#具有相同方法名称的多级继承c#
【发布时间】:2015-03-20 22:44:47
【问题描述】:

我在这里遇到了一个情况,这是交给我的现有代码,

class A
{
    public string helloworld()
    {
        return "A";
    }
}

class B : A
{
    public string helloworld()
    {

        return "B";
    }
}

class C: B
{
    public string hi()
    {
    if(condition1)
     {
        return helloworld(); // From class A
     }
    else
     {
        return helloworld(); // From class B
     }
    }
}

场景是这样的,在某种情况下,它应该从 A 类返回方法,否则它应该从 B 类返回方法 由于输出始终为“B”,我该如何实现这一目标

【问题讨论】:

  • 此代码无法编译,缺少 condition1。请展示一个编译并演示您描述的行为的示例。您可能还想查看 virtual 和 override 修饰符。
  • 你需要调用base.helloworld(),来调用A类中的方法。

标签: c# asp.net .net inheritance


【解决方案1】:

你可以这样做

class A
{
    public string helloworld()
    {
        return "A";
    }
}

class B : A
{
    public new string helloworld()
    {
        return "B";
    }
}

class C: B
{
   public string hi(bool condition)
   {
      if(condition)
      {
         A instance = this;
         return instance.helloworld(); // From class A
      }
      else
      {
          B instance = this;
          return instance.helloworld(); // From class B
      }
    }
}

如果您实现的方法隐藏了基类中的方法,编译器会警告您。告诉你的编译器这是故意使用 New 关键字。

要在基类中调用实现,您必须将实例类型转换为基类的类型。

【讨论】:

  • 你能解释一下上面的答案吗
【解决方案2】:
if (condition1)
{
    return ((A)this).helloworld(); // From class A
}
else
{
    return ((B)this).helloworld(); // From class B
}

另外,如果B 的源代码在您的控制之下,您应该将new 关键字添加到其helloworld 的实现中(或者更好的是,将其完全重命名以避免隐藏),但C.hi 中的解决方案将还是一样。

【讨论】:

  • 你能解释一下上面的答案吗
  • 多态性适用于动态类型:C 动态类型既不是A 也不是B,而是通过将C 的实例(即this)强制转换为AB 我们可以强制使用我们希望的动态类型,如原始代码中的 cmets 所示。如果没有强制转换,编译器只会退回到继承树上的第一个父级,B
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
相关资源
最近更新 更多