c# - 为什么在构造时提供了足够大的列表插入失败?

标签 c# list

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

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>.

简而言之List<T>.CountList<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/

相关文章:

linux - list_entry 返回值

python - 获取两个不同列表中同一索引处的一对值的出现次数

java - 获取List的Arraylist中与Arraylist匹配的数据

c# - 如何在不提交源代码的情况下将数据库凭据获取到 C# 应用程序中?

c# - 编辑器模板中的Ajax

c++ - 错误 : assignment to '_List_iterator<unsigned int,unsigned int &,unsigned int *>' from 'int'

java - 使用 foreach 在单行/表中显示多个列表

c# - DataGridView:如何选择整个列并取消选择其他所有内容?

c# - 需要对现有系统进行版本控制

c# - .net 核心包中缺少 ProtoBuf 格式化程序