MyClass[] array;
List<MyClass> list;

当一个比另一个更可取的情况是什么?,为什么?


当前回答

Lists in .NET are wrappers over arrays, and use an array internally. The time complexity of operations on lists is the same as would be with arrays, however there is a little more overhead with all the added functionality / ease of use of lists (such as automatic resizing and the methods that come with the list class). Pretty much, I would recommend using lists in all cases unless there is a compelling reason not to do so, such as if you need to write extremely optimized code, or are working with other code that is built around arrays.

其他回答

实际上,我只是想添加一个链接,我很惊讶还没有提到:Eric的Lippert的博客条目“数组被认为有点有害”。

您可以从标题中判断,它建议在任何可行的地方使用集合——但正如Marc正确地指出的那样,在很多地方,数组确实是唯一可行的解决方案。

尽管其他答案推荐List<T>,但在处理以下问题时,您将希望使用数组:

图像位图数据 其他底层数据结构(如网络协议)

因为没有人提到:在c#中,数组是一个列表。MyClass[]和List<MyClass>都实现了IList<MyClass>。(例如void Foo(IList<int> Foo)可以像Foo(new[]{1,2,3})或Foo(new List<int>{1,2,3})一样调用)

因此,如果你正在编写一个接受List<MyClass>作为参数的方法,但只使用功能的子集,你可能想声明为IList<MyClass>,以方便调用者。

细节:

为什么数组实现IList? 如何在c#数组部分实现IList<T>?

数组Vs.列表是典型的可维护性Vs.性能问题。几乎所有开发人员都遵循的经验法则是,您应该兼顾两者,但当两者发生冲突时,请选择可维护性而不是性能。该规则的例外情况是当性能已经被证明是一个问题时。如果你把这个原则应用到数组Vs.列表中,你会得到这样的结果:

使用强类型列表,直到遇到性能问题。如果遇到性能问题,请决定是否使用数组对解决方案的性能更有利,而不是在维护方面对解决方案造成损害。

Lists in .NET are wrappers over arrays, and use an array internally. The time complexity of operations on lists is the same as would be with arrays, however there is a little more overhead with all the added functionality / ease of use of lists (such as automatic resizing and the methods that come with the list class). Pretty much, I would recommend using lists in all cases unless there is a compelling reason not to do so, such as if you need to write extremely optimized code, or are working with other code that is built around arrays.