gpt4 book ai didi

c# - List<> Capacity 返回的项目多于添加的项目

转载 作者:可可西里 更新时间:2023-11-01 07:59:29 28 4
gpt4 key购买 nike

List<T> 上有几个属性这似乎与列表中的项目数量有关 - Capacity , Count (作为属性和方法存在)。这非常令人困惑,尤其是与 Array 相比那只有 Length .

我正在使用 List.Capacity但它给出了意想不到的结果:

List <string> fruits = new List<string>();
fruits.Add("apple");
fruits.Add("orange");
fruits.Add("banana");
fruits.Add("cherry");
fruits.Add("mango");
Console.WriteLine("the List has {0} items in it.", fruits.Capacity);

当我运行它时,控制台显示:

the List has 4 items in it.

我不明白为什么显示 Capacity 8 个,当我只添加 5 个项目时。

最佳答案

列表的Capacity表示列表当前为当前对象和要添加到其中的对象预留了多少内存。列表的 Count 是实际添加到列表中的项目数。

关于c# - List<> Capacity 返回的项目多于添加的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2485139/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com