[英]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.