相关疑难解决方法(0)

为什么((IList <T>)数组).ReadOnly = True但是((IList)数组).ReadOnly = False?

我知道在.NET中,所有数组都派生自System.Array并且System.Array类实现IList,ICollectionIEnumerable.实际的数组类型也实现IList<T>,ICollection<T>IEnumerable<T>.

这意味着如果你有一个String[],那么那个String[]对象也是a System.Collections.IList和a System.Collections.Generic.IList<String>;.

不难看出为什么那些IList会被认为是"ReadOnly",但令人惊讶的是......

String[] array = new String[0];
Console.WriteLine(((IList<String>)array).IsReadOnly); // True
Console.WriteLine(((IList)array).IsReadOnly); // False!
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,尝试通过Remove()RemoveAt()方法删除项会导致NotSupportedException.这表明两个表达式都对应于ReadOnly列表,但IList的ReadOnly属性不返回预期值.

怎么会?

.net c# arrays generics

21
推荐指数
2
解决办法
1339
查看次数

标签 统计

.net ×1

arrays ×1

c# ×1

generics ×1