【问题标题】:Can we change grand parent class's method definitions?我们可以更改祖父类的方法定义吗?
【发布时间】:2018-07-06 10:43:28
【问题描述】:

我正在研究某个问题,发现里面有一些有趣的问题。

让我用一个例子来解释(C#代码)

public class A: IA
{
    protected abstract void Append(LoggingEvent loggingEvent)
    { 
          //Some definition
    }
}


public class B: A
{
    protected override void Append(LoggingEvent loggingEvent)
    { 
          //override definition
    }
}



public class MyClass: B
{
    //Here I want to change the definition of Append method.
}

A 类和 B 类属于某个库,我无法控制更改这些类。

【问题讨论】:

  • 您可以再次覆盖。尝试验证非常简单。
  • @HimBromBeere - Append() 保持虚拟,直到你把它封印。
  • 请注意, A 中的 Append() 不能像您的示例那样在其中包含代码。它要么是一个没有实现的抽象方法,要么如果你想在那里放一些东西,你可以将它声明为虚拟的。

标签: c# oop inheritance polymorphism overriding


【解决方案1】:

由于这里层次结构中的方法都不是sealed,您可以继续自己覆盖该方法:

public class MyClass: B
{
    protected override void Append(LoggingEvent loggingEvent)
    { 
          // New logic goes here...
    }
}

【讨论】:

    【解决方案2】:

    根据我的研究,我已经分享了以下解决方案,但根据我的看法对您分享的代码进行了一些后续更改,因为问题中的代码在少数情况下无效。

    1. 添加了一个空的接口 IA,因为 A 类没有实现任何 public 方法。
    2. 将 A 类定义为抽象类,因为任何非抽象类都不能定义抽象方法。
    3. 删除了 A 类中 Append 方法的主体,作为抽象方法不能有主体。

      public interface IA
      {
      
      }
      
      public abstract class A : IA
      {
          protected abstract void Append();
      
      }
      
      public class B : A
      {
          protected override void Append()
          {
              //override definition
          }
      }
      
      public class MyClass : B
      {
          //Here I want to change the definition of Append method.
      
          //You can do is hide the method by creating a new method with the same name
          public new void Append() { }
      }
      

    答案:您不能覆盖非虚拟方法。您可以做的最接近的事情是通过创建具有相同名称的新方法来隐藏该方法,但这是不可取的,因为它违反了良好的设计原则。 但即使隐藏一个方法也不会给您提供执行时间多态的方法调用调度,就像真正的虚拟方法调用那样。

    【讨论】:

    • Abstract methods are implicitly virtual. 隐藏方法正是 OP不想要做的。
    • @BJMyers 我完全同意你的看法。这个问题本身并不是很准确。上面的答案附带了对问题的可能更正,在答案的最后,我强调不建议使用方法隐藏。感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多