gpt4 book ai didi

c# - 为什么 List 类型会以这种方式表现?

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:03 25 4
gpt4 key购买 nike

这是一个小程序,用于添加、删除、插入 items(double) 到 Ilist 集合中。

 class ProgramL
{
static void Main(string[] args)
{
IList<double> myList = new List<double>();
myList.Add(1.54);
myList.Add(56.54);
myList.Insert(1,58.54);
myList.Add(11.44);
myList.Add(121.44);
myList.Add(111.44);
myList.Add(1221.44);
myList.Add(1331.44);
myList.Add(161.44);
myList.Add(21.58);
myList.Remove(21.58);
Console.ReadLine();
}
}

所以在添加、插入和删除操作之后正好剩下 9 个项目。
但是根据图片为什么列表包含16个项目。最后 7 项初始化为 0.0 值。

enter image description here

有人可以向我解释一下吗?

谢谢

最佳答案

有两个数字:

  • Count - 添加到列表中的实际元素数量
  • Capacity - 用于在后台存储元素的数组大小

  • 这是为了提高性能并减少底层数组的分配数量 List<T>用于存储元素。

    当您实例化列表并添加第一个元素时,它是使用初始容量(4 个元素)创建的。当您添加元素并且现有容量不足时,底层数组将被重新分配以包含两倍的元素。那是因为重新分配数组非常昂贵,并且您不希望每次将元素添加到列表时都发生这种情况。

    您可以使用 TrimExcess使底层数组大小更接近集合中项目数的方法。

    This method can be used to minimize a collection's memory overhead if no new elements will be added to the collection. The cost of reallocating and copying a large List<T> can be considerable, however, so the TrimExcess method does nothing if the list is at more than 90 percent of capacity. This avoids incurring a large reallocation cost for a relatively small gain.

    关于c# - 为什么 List<double> 类型会以这种方式表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544368/

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