![](/img/trans.png)
[英]Is it possible to force explicit implementation of an interface (or parts of it)?
[英]force explicit interface implementation
假设我们有一个接口IFoo
:
interface IFoo {
void DoSomething();
}
现在我们有了一个实现类,该实现类在其构造函数中调用此方法:
class MyBase : IFoo {
MyBase() { this.DoSomething(); }
void DoSomething() { /* ... */ }
}
最后,我们有一个继承MyBase
的类,但shell提供了接口IFoo
另一种实现。 但是在调试时,我意识到构造函数只能访问我了解的MyBase
上的实现。 确保正确实现接口,我可以使用((IFoo) this).DoSomething();
从构造函数中显式调用接口方法((IFoo) this).DoSomething();
class MyDerived : MyBase, IFoo {
void DoSomething() { /* ... */ }
}
但是,我该如何强制该方法在使用之前必须强制转换为该接口? 我知道我可以在两个类中显式实现该接口,但是谁强迫我这样做呢? 因此,我们最终得出这样的结论:我该如何强迫继承我的类的人显式实现我的接口?
编辑:另一种方法是在MyBase
中使DoSomething
虚拟化,并忽略实现IFoo
的派生类。 但是我得到R#-警告然后在构造函数内调用虚拟成员。
这就是我要做的,将基类中的方法标记为虚方法,以便可以在子类中将其覆盖。 子类不需要显式实现接口,因为它继承了父类的行为。
interface IFoo {
void DoSomething();
}
class MyBase : IFoo {
MyBase() { this.DoSomething(); }
**virtual** void DoSomething() { /* ... */ }
}
class MyDerived : MyBase {
**override** void DoSomething() { /* ... */ }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.