List<int> list = new List(5);
为什么这样:
list.insert(2,3);
失败,出现以下错误:
Index must be within the bounds of the List.
提供初始尺寸有什么意义?
解决方法
Initializes a new instance of the
List<T>@H_301_21@ class that is empty and has the specified initial capacity.
如果您继续通过MSDN条目到备注部分,您将找到为什么提供此构造函数重载(再次强调我的):
The capacity of a
List<T>@H_301_21@ is the number of elements that the
List<T>@H_301_21@ can hold. As elements are added to a
List<T>@H_301_21@,the capacity is automatically increased as required by reallocating the internal array.
If the size of the collection can be estimated,specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the
List<T>@H_301_21@.
简而言之,列表< T> .Count与List< T> .Capacity(“如果Count在添加元素时超过容量,则容量增加……”)不同.
您收到异常是因为列表仅逻辑上包含您添加的项目,更改容量不会更改逻辑存储的项目数.如果您将List< T> .Capacity设置为小于List< T> .Count,我们可以测试此行为的另一个方向:
Unhandled Exception: System.ArgumentOutOfRangeException: capacity was less than the current size. Parameter name: value at System.Collections.Generic.List`1.set_Capacity(Int32 value)
或许创建您正在寻找的行为:
public static List<T> CreateDefaultList<T>(int entries) { return new List<T>(new T[entries]); }