如果我们有如下变量声明:
List<int> list = new List(5);
为什么会这样:
list.insert(2, 3);
失败并出现以下错误:
Index must be within the bounds of the List.
提供初始大小有什么意义?
最佳答案
所有初始大小都是provide a hint to the implementation to have at least a given capacity .它不会创建一个充满 N
的列表默认条目;强调我的:
Initializes a new instance of the
List<T>
class that is empty and has the specified initial capacity.
如果您继续浏览 MSDN 条目的备注部分,您会发现提供此构造函数重载的原因(再次强调我的):
The capacity of a
List<T>
is the number of elements that theList<T>
can hold. As elements are added to aList<T>
, 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>
.
简而言之List<T>.Count
与 List<T>.Capacity
不同(“如果在添加元素时 Count 超过 Capacity,则容量增加...”)。
您收到异常是因为该列表仅逻辑上包含您添加的项目,更改容量不会更改逻辑上存储的项目数。如果你要设置 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]);
}
关于c# - 为什么在构造时提供了足够大的列表插入失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8729921/