的indexer與明確的實施接口的實現,所以你只能將能夠訪問它,如果你這樣做:
IList<int> b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
b[2] = 3;
或
var b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
((IList<int>)b)[2] = 3;
當然,它會失敗,然後在執行時...
這完全是蓄意的,有幫助的 - 這意味着,當編譯器知道這是一個ReadOnlyCollection
,功能不支持位是不可用對你有幫助,可以讓你遠離執行時間的失敗。
雖然這是一個有趣且相對不尋常的步驟,但實際上隱式地實現了屬性/索引器的一半,明確地實現了一半屬性/索引器。
相反,我以前的想法,我相信ReadOnlyCollection<T>
實際上明確地實現了整個索引,但還提供公共只讀索引。換句話說,它是這樣的:
T IList<T>.this[int index]
{
// Delegate interface implementation to "normal" implementation
get { return this[index]; }
set { throw new NotSupportedException("Collection is read-only."); }
}
public T this[int index]
{
get { return ...; }
}
好的,但我如何使用顯式實現複製ReadOnlyCollection的功能。我看不出如何從界面中刪除方法或屬性。 – 2009-09-11 09:47:04
@EsbenP:你不能從接口中移除一個方法......但是你可以只在引用的靜態類型是接口而不是實現接口的類時纔可用。 – 2009-09-11 10:14:42
好吧,如果我有兩個索引,他們實施的IList的一個明確它的工作原理 牛逼的IList。這[INT指數] { 得到 { 返回源[指數] } set { throw new NotImplementedException(); } } 公共Ť此[INT指數] { 得到 { 返回源[指數]; } } –
2009-09-11 10:23:12