为什么在构造上提供足够的尺寸时列表插入失败?

Eri*_*rix 6 c# list

如果我们有以下变量声明:

List<int> list = new List(5);
Run Code Online (Sandbox Code Playgroud)

为什么这样:

list.insert(2, 3);
Run Code Online (Sandbox Code Playgroud)

失败,出现以下错误:

Index must be within the bounds of the List.
Run Code Online (Sandbox Code Playgroud)

提供初始尺寸有什么意义?

use*_*116 8

所有初始大小确实为实现提供了至少具有给定容量的提示.它不会创建一个填充N默认条目的列表; 强调我的:

初始化List<T>该类的新实例,该实例为空且具有指定的初始容量.

如果您继续通过MSDN条目到备注部分,您将找到为什么提供此构造函数重载(再次强调我的):

a的容量List<T>List<T>可以容纳的元素的数量.当元素添加到a时List<T>,通过重新分配内部数组,容量会根据需要自动增加.

如果可以估计集合的大小,则指定初始容量消除了在向元素添加元素的同时执行大量调整大小操作的需要List<T>.

简而言之List<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)
Run Code Online (Sandbox Code Playgroud)

或许创建您正在寻找的行为:

public static List<T> CreateDefaultList<T>(int entries)
{
    return new List<T>(new T[entries]);
}
Run Code Online (Sandbox Code Playgroud)