【发布时间】:2010-09-30 15:38:54
【问题描述】:
阅读有关在 C# 中创建只读原始向量的问题(基本上,您不能这样做),
public readonly int[] Vector = new int[]{ 1, 2, 3, 4, 5 }; // You can still changes values
我了解了ReadOnlyCollectionBase。这是允许访问但不修改其位置的对象容器的基类。 Microsoft Docs 中甚至有一个示例。
ReadOnlyCollectionBase Class - Microsoft Docs
我稍微修改了示例以使用任何类型:
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?我错过了吗?它在哪里?
谢谢。
【问题讨论】:
-
2015 年更新:.NET 4.5 现在有 ImmutableList msdn.microsoft.com/en-us/library/dn467185(v=vs.111).aspx
标签: c# readonly generic-collections