为什么C#的System.Collections库中没有ReadOnlyList <t>类?</t>

时间:2010-09-30 15:38:55

标签: c# readonly generic-collections

阅读在C#中创建只读原始向量的问题(基本上,你不能这样做),

public readonly int[] Vector = new int[]{ 1, 2, 3, 4, 5 }; // You can still changes values

我了解了 ReadOnlyListBase 。这是对象容器的基类,可以访问但不修改其位置。甚至在 Microsoft msdn 中也有一个例子。

http://msdn.microsoft.com/en-us/library/system.collections.readonlycollectionbase.aspx

我稍微修改了 msdn 中的示例以使用任何类型:

public class ReadOnlyList<T> : ReadOnlyCollectionBase {
    public ReadOnlyList(IList sourceList)  {
      InnerList.AddRange( sourceList );
    }

    public T this[int index]  {
      get  {
         return( (T) InnerList[ index ] );
      }
    }

    public int IndexOf(T value)  {
      return( InnerList.IndexOf( value ) );
    }



    public bool Contains(T value)  {
      return( InnerList.Contains( value ) );
    }

}

......它有效。我的问题是,为什么在C#的标准库中不存在这个类,可能在System.Collections.Generic中?我错过了吗?它在哪里? 谢谢。

1 个答案:

答案 0 :(得分:27)

ReadOnlyCollection<T>,这是上述的通用版本。

您可以通过调用list.AsReadOnly()直接从List<T>创建一个。