ReadOnlyCollection有什么神奇之处吗?

Esb*_*sen 11 .net interface readonly-collection

有这个代码......

var b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
b[2] = 3;
Run Code Online (Sandbox Code Playgroud)

我在第二行遇到编译错误.我希望自ReadOnlyCollection<T>实现以来有一个运行时错误,IList<T>并且this[T]IList<T>接口中有一个setter .

我试图复制ReadOnlyCollection的功能,但删除setter this[T]是一个编译错误.

Jon*_*eet 16

索引与显式接口实现来实现,所以你只能如果你访问它:

IList<int> b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
b[2] = 3;
Run Code Online (Sandbox Code Playgroud)

要么

var b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
((IList<int>)b)[2] = 3;
Run Code Online (Sandbox Code Playgroud)

当然,它会在执行时失败......

这是完全有意识和有用的 - 这意味着当编译器知道它是a时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 ...; }
}
Run Code Online (Sandbox Code Playgroud)