清单<>容量比返回添加更多项目 [英] List<> Capacity returns more items than added

查看:112
本文介绍了清单<>容量比返回添加更多项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关于列表与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.

我不明白为什么它呈现出容量

I don't understand why its showing a Capacity of 8, when I only added 5 items.

推荐答案

容量代表多少内存名单,目前已为当前对象预留和对象添加到它。列表中的计数是多少个项目实际上已经添加到列表中。

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.

这篇关于清单&LT;&GT;容量比返回添加更多项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆