为什么((IListT)数组).ReadOnly = True但为什么((IList)array).ReadOnly = False? [英] Why does ((IList<T>)array).ReadOnly = True but ((IList)array).ReadOnly = False?
问题描述
我知道在.NET中所有数组都是从System.Array派生的,并且System.Array类实现了 IList
, ICollection
和 IEnumerable
。实际的数组类型还实现 IList< T>
, ICollection< T>
和 IEnumerable< T> ;
。
I know that in .NET all arrays derive from System.Array and that the System.Array class implements IList
, ICollection
and IEnumerable
. Actual array types also implement IList<T>
, ICollection<T>
and IEnumerable<T>
.
这意味着,例如,如果您有 String []
,那么 String []
对象也是 System.Collections.IList
和 System.Collections.Generic.IList< String>
;。
This means that if you have, for example, a String[]
, then that String[]
object is also a System.Collections.IList
and a System.Collections.Generic.IList<String>
;.
不难理解为什么将这些IList视为只读,但是令人惊讶地……
It's not hard to see why those IList's would be considered "ReadOnly", but surprisingly...
String[] array = new String[0];
Console.WriteLine(((IList<String>)array).IsReadOnly); // True
Console.WriteLine(((IList)array).IsReadOnly); // False!
在两种情况下,尝试通过 Remove()删除项目
和 RemoveAt()
方法将导致NotSupportedException。这可能表明两个表达式都对应于ReadOnly列表,但是IList的 ReadOnly
属性不会返回预期值。
In both cases, attempts to remove items via the Remove()
and RemoveAt()
methods results in a NotSupportedException. This would suggest that both expressions correspond to ReadOnly lists, but IList's ReadOnly
property does not return the expected value.
推荐答案
来自 MSDN :
Array实现了IsReadOnly属性,因为
System.Collections.IList接口需要它。只读数组不允许
在创建
数组后允许添加,删除或修改元素。
Array implements the IsReadOnly property because it is required by the System.Collections.IList interface. An array that is read-only does not allow the addition, removal, or modification of elements after the array is created.
如果需要只读集合,请使用实现System.Collections.IList接口的System.Collections类
。
If you require a read-only collection, use a System.Collections class that implements the System.Collections.IList interface.
如果将数组强制转换或转换为一个IList接口对象,
IList.IsReadOnly属性返回false。但是,如果您强制转换或
将数组转换为IList< T> ;,界面,IsReadOnly属性
返回true。
If you cast or convert an array to an IList interface object, the IList.IsReadOnly property returns false. However, if you cast or convert an array to a IList<T> interface, the IsReadOnly property returns true.
此处的只读表示无法修改数组中的项目,并且这就是为什么它返回false的原因。
Read-only here means that the items in the array cannot be modified and that's why it returns false.
还可以看看 Array.IsReadOnly不一致,具体取决于接口的实现方式。
这篇关于为什么((IListT)数组).ReadOnly = True但为什么((IList)array).ReadOnly = False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!