有这个代码...
var b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
b[2] = 3;
我在第二行收到编译错误。我预计会出现运行时错误,因为
ReadOnlyCollection<T>
实现 IList<T>
和 this[T]
在 IList<T>
中有一个二传手界面。我试图复制 ReadOnlyCollection 的功能,但是从
this[T]
中删除了 setter是编译错误。
最佳答案
indexer是通过显式接口(interface)实现实现的,因此您只有在执行以下操作时才能访问它:
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>
实际上显式地实现了整个索引器,但也提供了一个公共(public)的只读索引器。换句话说,它是这样的: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 ...; }
}
关于.net - ReadOnlyCollection 有什么神奇之处吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1409854/