インデクサーは明示的なインターフェイスの実装で実装されているため、次の場合にのみアクセスできます。
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 ...; }
}