清单<>容量比返回添加更多项目 [英] List<> Capacity returns more items than added
问题描述
有关于列表与LT几个属性; T>
这似乎与列表中的项目数量 - 容量
,计数
(这是目前作为一个属性和方法)。这是相当混乱特别是阵列
刚长度
比
There are several properties on List<T>
that seem to be related to number of items in the list - Capacity
, Count
(which is present as a property and a method). This is quite confusing especially compared with Array
that has just Length
.
我用 List.Capacity
,但它给了意想不到的结果:
I'm using List.Capacity
but it gives unexpected result:
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);
当我运行这个控制台显示:
when I run this the Console displays:
the List has 4 items in it.
我不明白为什么它呈现出容量$ 8,当我只加了5项C $ C>。
I don't understand why its showing a Capacity
of 8, when I only added 5 items.
推荐答案
的容量$名单C $ C>代表多少内存名单,目前已为当前对象预留和对象添加到它。列表中的
计数
是多少个项目实际上已经添加到列表中。
The Capacity
of the list represents how much memory the list currently has set aside for the current objects and objects to be added to it. The Count
of the list is how many items have actually been added to the list.
这篇关于清单<>容量比返回添加更多项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!