什么时候在 C# 中使用 ArrayList 而不是 array[]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/412813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:24:30  来源:igfitidea点击:

When to use ArrayList over array[] in c#?

c#arraysarraylist

提问by inspite

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

我经常使用 anArrayList而不是 'normal' array[]

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

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

采纳答案by Bob

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.

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

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.

ArrayLists 不是强类型的,每次插入或重试都需要强制转换才能恢复到原始类型。如果您需要一种方法来获取特定类型的列表,则 ArrayLists 无法实现,因为您可以传入包含任何类型的 ArrayList。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.

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

回答by Michael Borgwardt

Unless that part of the code is absolutely performance-critical, using ArrayList is perfectly fine.

除非那部分代码对性能至关重要,否则使用 ArrayList 完全没问题。

回答by Frederick The Fool

Better still, wherever you use ArrayList, use the List<T>generic collection instead. It is more strongly typed than the former.

更好的是,无论您在何处使用ArrayList,请改用List<T>泛型集合。它的类型比前者强。

回答by Spodi

Well for one, if you only intend to handle a specific type, you shouldn't use an ArrayList. For example, if you only expect an array of bytes, you should only accept an array of bytes.

一方面,如果您只想处理特定类型,则不应使用 ArrayList。例如,如果您只需要一个字节数组,则应该只接受一个字节数组。

Only time I would think you may even think of using an ArrayList is instead of List.

只有一次我认为您甚至可能会想到使用 ArrayList 而不是 List。

回答by Tamas Czinege

In addition to Bob's and Frederick's response, I would like to point it out that while arrays have covariance, generic lists do not. For example, an array of type MyChildClass[]can be easily casted to MyParentClass[], while List<MyChildClass>cannot be casted to List<MyParentClass>, at least not directly.

除了 Bob 和 Frederick 的回应,我想指出的是,虽然数组具有协方差,但泛型列表没有。例如,一个类型的数组MyChildClass[]可以很容易地转换为MyParentClass[],而List<MyChildClass>不能转换为List<MyParentClass>,至少不能直接转换。

If you need covariance, either use arrays, use LINQ's Cast() method or some other means to cast each item individually or wait for C# 4.

如果您需要协方差,请使用数组、使用 LINQ 的 Cast() 方法或其他一些方法来单独转换每个项目或等待 C# 4

回答by Rumen Georgiev

The array's size is static, so if you do know the size at design time, use array. It is supposed to work faster, but I haven't tested it myself. If you need to change the count of objects frequently (adding or removing objects from the collection) use ArrayList or better the generic List from .NET 2. It's also easier to use, so if performance is not crucial, you can always use List.

数组的大小是静态的,因此如果您在设计时确实知道大小,请使用数组。它应该工作得更快,但我自己还没有测试过。如果您需要频繁更改对象的数量(从集合中添加或删除对象),请使用 ArrayList 或更好的 .NET 2 中的通用 List。它也更易于使用,因此如果性能不是很重要,您可以始终使用 List。

回答by Marc Gravell

One other thought here is mutation; an array (T[]) is fully mutable, and cannot be protected. List<T>doesn't provide any useful extension points, but things like Collection<T>(or many other IList<T>implementations) allow you to add code, for example, to check items before they are added; likewise, you can have readonly IList<T>implementations, which is useful for thread safety where immutability is desirable.

这里的另一种想法是突变;数组 ( T[]) 是完全可变的,不能被保护。List<T>不提供任何有用的扩展点,但诸如Collection<T>(或许多其他IList<T>实现)之类的东西允许您添加代码,例如,在添加项目之前检查项目;同样,您可以拥有只读IList<T>实现,这对于需要不变性的线程安全非常有用。

I tend to use arrays either in internal method logic (perhaps as a local variable), as paramsarguments, or in a few highly optimised cases where I know the length of the items, and I know the code choosesnot to mutate it (as a private field). Other than that, List<T>etc tend to be more common, as they have much less overhead when adding/removing items.

我倾向于在内部方法逻辑中使用数组(可能作为局部变量)、作为params参数,或者在一些我知道项目长度的高度优化的情况下使用数组,并且我知道代码选择不改变它(作为一个私人领域)。除此之外,List<T>等等往往更常见,因为它们在添加/删除项目时的开销要少得多。

回答by Ronald Blaschke

I'm answering this from a Java perspective, but it's the same basic issue. You should not feel guilty using higher abstractions. After all, you are using Strings instead of char[], or even byte[]? I'd even suggest to go one step further and use the Listinterface where possible. The only reason to go one step down is for performance reasons.

我是从 Java 的角度来回答这个问题的,但这是相同的基本问题。使用更高的抽象,您不应该感到内疚。毕竟,您使用String的是s 而不是char[], 甚至byte[]? 我什至建议更进一步,并List在可能的情况下使用该界面。退一步的唯一原因是出于性能原因。

Using the higher collection abstraction has many advantages. You can add decorators to make the List read-only, make it fixed size, check items that enter or leave the collection or use views (see GetRangein C# and subListin Java.)

使用更高的集合抽象有很多优点。您可以添加装饰器使 List 只读、固定大小、检查进入或离开集合的项目或使用视图(参见GetRangeC# 和subListJava。)

By the way, an ArrayListshould always be based on a primitive array, otherwise the name is wrong. The operations are usually implemented just how you would expect when using a primitive array. If a linked list is used it's usually named just that -- LinkedList. That's also an advantage of using the interface: You can change your mind about the used implementation later on.

顺便说一句, anArrayList应该始终基于原始数组,否则名称是错误的。这些操作通常按照您在使用原始数组时所期望的方式实现。如果使用链表,它通常被命名为 -- LinkedList。这也是使用接口的一个优势:您可以稍后改变对所用实现的看法。

There are a few things that make the use of collections clunky. One caveat is that the collections are usually based on objects, and the languages have a considerable gap between primitive and object types. The limited generics don't help much either. Still, I recommend the collections over arrays unless there's a good reason otherwise.

有一些事情使集合的使用变得笨拙。一个警告是集合通常基于对象,并且语言在原始类型和对象类型之间存在相当大的差距。有限的泛型也没有多大帮助。尽管如此,我还是推荐集合而不是数组,除非有充分的理由。

For primitive values you may also consider using a primitive collection library, for example GNU Trove. Don't know if there's anything similar for C#, though.

对于原始值,您还可以考虑使用原始集合库,例如GNU Trove。不过,不知道 C# 是否有类似的东西。

回答by doekman

Fabulous Adventures In Codinghas written a piece Arrays considered somewhat harmful. It's a really interesting read.

Fabulous Adventures In Coding写了一篇Arrays 被认为有些有害。这是一个非常有趣的阅读。

回答by endless

If you need an array of primitive types use Array for better performance as it will avoid autoboxing and unboxing. But only if you know the size you want ahead of time.

如果您需要基本类型数组,请使用 Array 以获得更好的性能,因为它将避免自动装箱和拆箱。但前提是你提前知道你想要的尺寸。