c# - IsReadOnly 是否禁止您在内部更改自定义 IList 对象?

标签 c# .net

备注 IList.IsReadOnly说明如下:

A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created.

这是否意味着实现 IList 的自定义类不能在内部添加或删除元素,或者它只是禁止用户使用接口(interface)方法来执行此操作?

如果允许内部修改,这是否意味着期望 IsReadOnly 为 true 的 IList 永不更改的代码在本质上是错误的?

如果不允许内部修改,是否意味着不可能编写一个有效的IList,它可以在内部更改,但不允许用户修改它?

最佳答案

https://msdn.microsoft.com/en-us/library/cc645181%28v=vs.110%29.aspx

A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.

对于另一种类型,没有什么可以阻止您将真正不可变的集合公开为 IList<T>该属性返回 true,但您不必这样做。

我们还可以看到框架库中的案例为 IsReadOnly 返回 true通常允许改变内部集合。

List<int> initialList = new List<int> { 1 };
IList<int> readOnly = new ReadOnlyCollection<int>(initialList);
Console.WriteLine(readOnly.Count); // 1
Console.WriteLine(readOnly.IsReadOnly); // True
initialList.Add(2);
Console.WriteLine(readOnly.Count); // 2

真的,IsReadOnly告诉你像 Add 这样的变异方法并且索引器的 setter 端将失败,而不是对象在任何情况下都是不可变的。

关于这方面的一个有趣的考虑:框架库中的某些地方本身需要只读列表,这些列表确实是真正只读的。他们的公共(public)接口(interface)返回 ReadOnlyCollection<T>IReadOnlyList<T> (例如 BlockExpression.Expressions 返回 ReadOnlyCollection<T> )但他们不信任传递给他们的只读集合。他们使用一个名为 TrueReadOnlyCollection<T> 的内部类型它被创建为一个新数组的包装器,在构造时被复制,所以没有其他东西可以改变它。该类型被认为永远不会改变,因此可以在使用之间共享,但所有其他情况都不会。

关于c# - IsReadOnly 是否禁止您在内部更改自定义 IList 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452774/

相关文章:

c# - 在哪里可以找到生成数码迷彩图案的算法?

c# - 如何将 Expires Header 添加到 iis7 中的自定义文件?

c# - 检查网络状态

c# - 通过 xml 进行搜索的最快方法是什么

c# - 分析重复序列

c# - 自定义字典 ​​TryGetValue 找不到键

c# - 如何保护我的 .net winforms 程序集不受客户客户的影响

.net - 使用 OpenGL 直接绘制到 .NET 位图

c# - 强制接口(interface)实现检查异常

c# - 您如何看待在 C# 中使用属性作为对象初始值设定项?