c# – 当构造上提供足够的大小时,为什么列表插入失败?

如果我们有以下变量声明:
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 the List<T> can hold. As elements are added to a List<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>.

简而言之,列表< 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]);
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...