列表<>容量返回的项目多于添加的项目 [英] List<> Capacity returns more items than added

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

问题描述

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

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.

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

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

推荐答案

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

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天全站免登陆