次のコードを検討してください。
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
asをマークすると、のデフォルトの実装を呼び出すことができなくなり、.virtual
IChildInterface
DoWork()
StackOverflowException
virtual
から修飾子を削除するDoWork()
とBaseClass
、すべてが機能し、IChildInterface
のデフォルトの実装DoWork()
が呼び出されます。
そのような動作はバグですか、それとも仕様ですか?
一部の子クラスが の独自の実装を提供できるようにする方法はありますかDoWork()
(したがって、 の実装をオーバーライドしますBaseClass
) が、のデフォルトの実装を引き続き使用でき ますか?IChildInterface
DoWork()