這被稱爲「顯式接口實現」。其原因可能是例如命名衝突。
考慮接口IEnumerable
和IEnumerable<T>
。一個聲明瞭一個非泛型方法
IEnumerator GetEnumerator();
,另一個是通用的一個:
IEnumerator<T> GetEnumerator();
在C#它不允許有兩個方法與只在有返回類型不同,相同的名稱。所以,如果你實現這兩個接口,你需要聲明一個方法明確:
public class MyEnumerable<T> : IEnumerable, IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
... // return an enumerator
}
// Note: no access modifiers allowed for explicit declaration
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator(); // call the generic method
}
}
明確實現的接口方法不能對實例變量被稱爲:
MyEnumerable<int> test = new MyEnumerable<int>();
var enumerator = test.GetEnumerator(); // will always call the generic method.
如果要調用非-generic方法,您需要投test
到IEnumerable
:
((IEnumerable)test).GetEnumerator(); // calls the non-generic method
這似乎也是爲什麼在顯式實現中不允許訪問修飾符(如public
或private
)的原因:它在類型上不可見。
可以肯定的是,如果實現類具有相同簽名的方法,您可以區分它。 – Tobias
顯式接口實現不允許使用可見性修飾符。我很肯定你只是在你的問題中輸入錯誤,所以繼續編輯它。如果您認爲我錯了,如果您認爲「公共」真的存在,請隨時恢復,但那時您無法編譯。 – hvd