【发布时间】:2014-10-20 21:36:55
【问题描述】:
我知道在 .NET 中,所有数组都派生自 System.Array,并且 System.Array 类实现 IList、ICollection 和 IEnumerable。实际的数组类型也实现了IList<T>、ICollection<T> 和IEnumerable<T>。
这意味着,例如,如果您有一个String[],那么该String[] 对象也是一个System.Collections.IList 和一个System.Collections.Generic.IList<String>;。
不难看出为什么这些 IList 会被视为“只读”,但令人惊讶的是......
String[] array = new String[0];
Console.WriteLine(((IList<String>)array).IsReadOnly); // True
Console.WriteLine(((IList)array).IsReadOnly); // False!
在这两种情况下,尝试通过 Remove() 和 RemoveAt() 方法删除项目都会导致 NotSupportedException。这表明这两个表达式都对应于 ReadOnly 列表,但 IList 的 ReadOnly 属性没有返回预期值。
怎么会?
【问题讨论】:
-
我怀疑 Remove() 和 RemoveAt() 会抛出异常,因为这些操作意味着调整底层列表的大小,而 Resize 方法之外的数组不支持这一点 - 但这并不能回答您的主要问题问题。
-
@ErikForbes 认为你是对的。
AddonIList即使显然不是只读的,也会抛出Collection was of a fixed size的 Not Supported 异常 -
是的,我认为任何隐式更改底层数组大小的操作都会因该异常而失败。
-
@TyCobb 它声称对
IList<T>的强制转换正在实例化ReadOnlyCollection<T>,这是错误且具有误导性的。