开发者

C# Overriding a base class method more than one derived class down inheritance chain

I have an inheritance chain that consists of three classes A,B, and C, where A and B are abstract, and C is a concrete implementation of B.

I have a virtual method on the base abstract class A, Foo() that I would like to override in the concrete class C.

If I try and override just in Class C it is never picked up and always uses the default base class implementation, but if I override in both B & C, it only ever uses the B.Foo() implementation of the virtual method.

Do I have to declare something extra on B.Foo() other than 'override'?

Obviously these are simplified versions of my classes, but here are my method declarations:

abstract class A {
  protected virtual string Foo() {
    return "A";
  }
}

abstract class B : A {
  protected override string Foo() {
    return "B";
  }
}

class C : B {
  protec开发者_Python百科ted override string Foo() {
    return "C";
  }
}


Huh?

void Main()
{
    new C().DumpFoo(); // C
    A x=new C();
    x.BaseDumpFoo(); //C
}

abstract class A {
  protected virtual string Foo() {
    return "A";
  }
  public void BaseDumpFoo()
  {
    Console.WriteLine(Foo());
  }
}

abstract class B : A {
  protected override string Foo() {
    return "B";
  }
}

class C : B {
  protected override string Foo() {
    return "C";
  }
  public void DumpFoo()
  {
    Console.WriteLine(Foo());
  }
}

Output is C. Remove Foo implementation from B and the output is still C


The problem's that since B is overriding the method, when calling it from C, it never reaches to its implementation in the inheritance hierarchy
what you need to do is define the method in B as new (so that it overrides the implementation from A) and define it also as virtual (so that C can use it's own implementation you would have something like this

abstract class A
{
    protected virtual string Foo()
    {
        return "A";
    }
}

abstract class B : A
{
    protected new virtual string Foo()
    {
        return "B";
    }
}

class C : B
{
    protected override string Foo()
    {
        return "C";
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜