考虑代码:
class ChildClass : BaseClass {
public void Method1() {} //some other method
}
abstract class BaseClass : IChildInterface {
public
virtual //<- If we add virtual so that this method can be overridden by ChildClass, we get StackOverflowException and DoWork() implementation in IChildInterface is never called.
void DoWork() {
//base class specific implmentation
((IChildInterface)this).DoWork(); //call into default implementation provided by IChildInterface
}
}
interface IChildInterface : IBaseInterface {
void IBaseInterface.DoWork() {
//implmentation
}
}
interface IBaseInterface {
void DoWork();
}
问题是,如果我们标记DoWork()为BaseClass以便virtual它可以被子类覆盖,它会阻止它调用IChildInterface的默认实现DoWork(),从而导致StackOverflowException.
如果我们从中删除virtual修饰符,一切正常,并调用的默认实现。DoWork()BaseClassIChildInterfaceDoWork()
这种行为是错误还是设计使然?
有没有办法让一些子类提供他们自己的实现DoWork()(从而覆盖BaseClass的实现)但仍然能够使用 IChildInterface的默认实现DoWork()?