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

Bal*_*arq 23 c# readonly generic-collections

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

public readonly int[] Vector = new int[]{ 1, 2, 3, 4, 5 }; // You can still changes values
Run Code Online (Sandbox Code Playgroud)

我了解了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 ) );
    }

}
Run Code Online (Sandbox Code Playgroud)

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

Ree*_*sey 32

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

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