C# 沿继承链重写多个派生类的基类方法
我有一个继承链,由三个类 A、B 和 C 组成,其中 A 和 B 是抽象的,C 是 B 的具体实现。
我在基本抽象类 A 上有一个虚拟方法, Foo( )
,我想在具体的类 C 中重写。
如果我尝试仅在类 C 中重写,它永远不会被拾取,并且始终使用默认的基类实现,但如果我在 B 和 B 中都重写; C,它只使用虚拟方法的 B.Foo()
实现。
除了“覆盖”之外,我是否还必须在 B.Foo() 上声明一些额外的内容?
显然,这些是我的类的简化版本,但这是我的方法声明:
abstract class A {
protected virtual string Foo() {
return "A";
}
}
abstract class B : A {
protected override string Foo() {
return "B";
}
}
class C : B {
protected override string Foo() {
return "C";
}
}
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 {
protected override string Foo() {
return "C";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
啊?
输出是
C
。从B
中删除Foo
实现,输出仍然是C
Huh?
Output is
C
. RemoveFoo
implementation fromB
and the output is stillC
问题是,由于 B 正在重写该方法,因此当从 C 调用它时,它永远不会到达继承层次结构中的实现
你需要做的是将 B 中的方法定义为 new (以便它覆盖 A 的实现)并将其也定义为 virtual (以便 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