MyClass[] array;
List<MyClass> list;

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


当前回答

因为没有人提到:在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>?

其他回答

除非你真的关心性能,我的意思是,“你为什么使用。net而不是c++ ?”你应该坚持使用List<>。它更容易维护,并为您在幕后完成调整数组大小的所有繁琐工作。(如果有必要,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<string> arr = new List<string>();

arr.Add("string a");
arr.Add("string b");
arr.Add("string c");
arr.Add("string d");

arr[10] = "new string";

它生成一个异常。

相反,使用数组:

string[] strArr = new string[20];

strArr[0] = "string a";
strArr[1] = "string b";
strArr[2] = "string c";
strArr[3] = "string d";

strArr[10] = "new string";

但是对于数组,不会自动调整数据结构的大小。您必须手动或使用Array管理它。调整方法。

一个技巧是用一个空数组初始化List。

List<string> arr = new List<string>(new string[100]);

arr[10] = "new string";

但在这种情况下,如果你使用Add方法添加一个新元素,它将被注入到列表的末尾。

List<string> arr = new List<string>(new string[100]);

arr[10] = "new string";

arr.Add("bla bla bla"); // this will be in the end of List

大多数情况下,使用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<T>,但在处理以下问题时,您将希望使用数组:

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