为什么((IList<;T>;)array).ReadOnly=True,但((IList-array).RRe

本文关键字:True IList-array RRe array lt gt 为什么 IList ReadOnly | 更新日期: 2023-09-27 18:27:09

我知道在.NET中,所有数组都派生自System.Array,System.Array类实现IListICollectionIEnumerable。实际的数组类型还实现了IList<T>ICollection<T>IEnumerable<T>

这意味着,例如,如果您有String[],那么该String[]对象也是System.Collections.IListSystem.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属性没有返回预期值。

为什么?

为什么((IList<;T>;)array).ReadOnly=True,但((IList-array).RRe

这对我来说就像一个简单的错误:

  • 它显然不是只读的,因为索引器允许对其进行修改
  • 它不是执行到任何其他类型对象的转换

请注意,您不需要强制转换-有一个隐式转换:

using System;
using System.Collections.Generic;
class Test
{
    static void Main()
    {
        string[] array = new string[1];
        IList<string> list = array;
        Console.WriteLine(object.ReferenceEquals(array, list));
        Console.WriteLine(list.IsReadOnly);
        list[0] = "foo";
        Console.WriteLine(list[0]);
    }
}

ICollection<T>.IsReadOnlyIList<T>从中继承属性)记录为:

只读集合不允许在创建集合后添加、删除或修改元素。

虽然数组不允许添加或删除元素,但显然允许修改。

来自MSDN:

数组实现IsReadOnly属性,因为它是System.Collections.IList接口。只读数组不允许在创建数组。

如果需要只读集合,请使用System.Collections类实现System.Collections.IList接口的。

如果将数组强制转换或转换为IList接口对象IList.IsReadOnly属性返回false。但是,如果您铸造或将数组转换为IList<T>接口,IsReadOnly属性返回true。

这里的只读意味着不能修改数组中的项,这就是它返回false的原因。

还可以查看Array.IsReadOnly根据接口实现的不同而不一致。