加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:29:38 所属栏目:百科 来源:网络整理
导读:如果我们有以下变量声明: Listint list = new List(5); 为什么这样: list.insert(2,3); 失败,出现以下错误: Index must be within the bounds of the List. 提供初始尺寸有什么意义? 解决方法 所有初始大小都是 provide a hint to the implementation to
如果我们有以下变量声明:
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]);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读