备注 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/