![](/img/trans.png)
[英]How can class implement interface with one property also implement other interface
[英]How Can a Class Can Implement Interface without implement one Of the Functions?
我注意到TFS API中的一個類中有一個非常奇怪的行為,看起來像是破壞了語言的定義。
我試圖模仿它,但是沒有成功,我試圖實現集合,但是不讓使用該類的人來調用索引器二傳手,就像在WorkitemCollection類中所做的那樣。 重要的是,錯誤將在完成時而不是在運行時顯示,因此異常無效。 WorkitemCollection正在實現IReadOnlyList,后者正在實現Collection。 根據定義,Collection具有索引Public Get And Set。 但是此代碼返回了編譯錯誤:
WorkitemCollection wic=GetWorkitemCollection();
wic[0]=null;
為什么會這樣呢? 提前致謝。
解決方案是顯式接口實現 。 當您使用實現接口的類時,這實質上使該方法私有。 但是,仍然可以通過將類的實例強制轉換為實現接口來調用它,因此您仍然需要引發異常。
public class Implementation : IInterface
{
void IInterface.SomeMethod()
{
throw new NotSupportedException();
}
}
var instance = new Implementation();
instance.SomeMethod(); // Doesn't compile
var interfaceInstance = (IInterface)instance;
interfaceInstance.SomeMethod(); // Compiles and results in the
// NotSupportedException being thrown
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.