什么时候在 C# 中使用 ArrayList 而不是 array[]? [英] When to use ArrayList over array[] in c#?

查看:46
本文介绍了什么时候在 C# 中使用 ArrayList 而不是 array[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用 ArrayList 而不是普通的"array[].

I often use an ArrayList instead of a 'normal' array[].

当我使用 ArrayList 时,我感觉好像在作弊(或偷懒),什么时候可以在数组上使用 ArrayList?

I feel as if I am cheating (or being lazy) when I use an ArrayList, when is it okay to use an ArrayList over an array?

推荐答案

数组是强类型的,可以很好地用作参数.如果你知道你的集合的长度并且它是固定的,你应该使用一个数组.

Arrays are strongly typed, and work well as parameters. If you know the length of your collection and it is fixed, you should use an array.

ArrayList 不是强类型,每次插入或重试都需要强制转换才能恢复到原始类型.如果您需要一种方法来获取特定类型的列表,那么 ArrayLists 就不够用了,因为您可以传入包含任何类型的 ArrayList.ArrayLists内部使用了一个动态扩展的数组,所以当它达到它的容量时也有一个扩展内部数组大小的命中.

ArrayLists are not strongly typed, every Insertion or Retrial will need a cast to get back to your original type. If you need a method to take a list of a specific type, ArrayLists fall short because you could pass in an ArrayList containing any type. ArrayLists use a dynamically expanding array internally, so there is also a hit to expand the size of the internal array when it hits its capacity.

您真正想要使用的是一个通用列表,例如 List.这具有 Array 和 ArrayLists 的所有优点.它是强类型的,支持可变长度的项目.

What you really want to use is a generic list like List<T>. This has all the advantages of Array and ArrayLists. It is strongly typed and it supports a variable length of items.

这篇关于什么时候在 C# 中使用 ArrayList 而不是 array[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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