微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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]);
}

原文地址:https://www.jb51.cc/csharp/91369.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐