多态调用将转到基类而不是子类

时间:2019-02-15 05:58:06

标签: c# polymorphism

在类型为C的对象MethodX上,我期望B中的MethodY()调用(以问号突出显示)最终将调用C的MethodY。但是调试会话显示它正在调用A的MethodY()

我很困惑为什么。 B的MethodX()中的断点清楚地表明this是C类型的对象。我尝试了this.MethodY();并删除了虚拟/覆盖并使用new,结果相同。我是否对另一种语言感到困惑或是否忽略了某些内容?

public abstract class A {
  protected virtual void MethodY() {...}   // This one's being called.
}

public class B : A {
  protected override void MethodY() {...}

  public override void MethodX() {
     MethodY();   // ???
  }
}

public class C : B {
  protected override void MethodY() {...}   // But want this one to be called

  protected override void MethodX() {
    base.MethodX();
    ...
  }
}

1 个答案:

答案 0 :(得分:2)

  

我期望MethodY()中的B调用最终会调用C的{​​{1}}

可以

MethodY

输出

public abstract class A
{
    public virtual void MethodX()
      => Console.WriteLine("A - X");

    public virtual void MethodY()
      => Console.WriteLine("A - Y");
}

public class B : A
{
    public override void MethodY()
      => Console.WriteLine("B - Y");

    public override void MethodX()
    {
        Console.WriteLine("B - X");
        MethodY();
    }
}

public class C : B
{
    public override void MethodY()
      => Console.WriteLine("C - Y");

    public override void MethodX()
    {
        Console.WriteLine("C - X");
        base.MethodX();
    }
}

public static void Main()
{
    var c = new C();
    c.MethodX();
}

Full Demo Here