.net - ReadOnlyCollection 有什么神奇之处吗

标签 .net interface readonly-collection

有这个代码...

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/

相关文章:

javascript - 什么 dateTime 格式与 .NET 和 JS 兼容而无需进一步重新格式化?

java - 通知对象发生了某些事情 - 监听器对象?

c# - 我想我错过了 "Programming to an interface"概念的一些东西

c# - 为什么 IReadOnlyCollection 有 ElementAt 但没有 IndexOf

c# - 如何以只读方式传递字节数组?

.net - 使用 System.Threading.Task 将工作项排队到线程池

.net - 将 LINQ 数据上下文和非 linq 存储过程包装到事务中?

c# - 使用 Reflection.Emit 生成相互引用的类型

java - 将测试套件应用于接口(interface)的实现

python - 如何使字典只读?