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.

其他回答

大多数情况下,使用List就足够了。List使用内部数组来处理其数据,并在向List中添加比当前容量更多的元素时自动调整数组的大小,这使得它比需要事先知道容量的数组更容易使用。

有关c#中的列表的更多信息,请参阅http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5,或者只是反编译System.Collections.Generic.List<T>。

如果需要多维数据(例如使用矩阵或图形编程),则可能使用数组。

像往常一样,如果内存或性能是一个问题,测量它!否则,您可能会对代码做出错误的假设。

填充列表比填充数组更容易。对于数组,您需要知道数据的确切长度,但对于列表,数据大小可以是任何大小。你可以把一个列表转换成一个数组。

List<URLDTO> urls = new List<URLDTO>();

urls.Add(new URLDTO() {
    key = "wiki",
    url = "https://...",
});

urls.Add(new URLDTO()
{
    key = "url",
    url = "http://...",
});

urls.Add(new URLDTO()
{
    key = "dir",
    url = "https://...",
});

// convert a list into an array: URLDTO[]
return urls.ToArray();

如果我确切地知道我需要多少元素,比如我需要5个元素,而且只需要5个元素,那么我就使用数组。否则我只使用List<T>。

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

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

它完全取决于需要数据结构的上下文。例如,如果您正在创建供其他函数或服务使用的项,则使用List是完成该任务的最佳方式。

现在,如果你有一个项目列表,你只是想在网页上显示它们,数组是你需要使用的容器。