在c#中,数组列表和List<>有什么区别?
是不是只有List<>有类型而ArrayList没有?
在c#中,数组列表和List<>有什么区别?
是不是只有List<>有类型而ArrayList没有?
当前回答
ArrayList不是类型安全的,而List<T>是类型安全的。简单:)。
其他回答
要添加的另一个区别是线程同步。
ArrayList provides some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. List<T> does not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently.
更多信息在这里线程同步在.Net框架
To me its all about knowing your data. If I am continuing to expand my code on the basis of efficiency, I would have to choose the List option as a way of deciphering of my data w/o the unnecessary step of always wondering about types, especially 'Custom Types'. If the machine understands the difference and can determine on it's on what type of data I'm actually dealing with then why should I get in the way and waste time going thru the gyrations of 'IF THEN ELSE' determinations? My philosophy is to let the machine work for me instead of me working on the machine? Knowing the unique differences of different object code commands goes a long way in making your code as efficient.
汤姆•约翰逊 (一项…一个出口)
再加上以上几点。在64位操作系统中使用ArrayList占用的内存是32位操作系统的2倍。同时,泛型列表list <T>占用的内存比ArrayList少得多。
例如,如果我们在32位中使用一个19MB的数组列表,那么在64位中它将占用39MB。但是如果你有一个32位的8MB的通用列表list <int>,它在64位只需要8.1MB,这与ArrayList相比相差了481%。
来源:数组列表与通用列表的基本类型和64位
简单的答案是,
数组列表是非泛型的
它是一个对象类型,因此您可以在其中存储任何数据类型。 可以在数组列表中存储任意值(值类型或引用类型),例如string、int、employee和object。(注意,) 装箱和开箱将会发生。 不类型安全。 它更老。
列表是通用的
它是类型的类型,因此您可以在运行时指定T。 根据声明,您只能存储类型为T的值(字符串或int或employee或object)。(注意或) 装箱和开箱不会发生。 类型安全。 它更新。
例子:
ArrayList arrayList = new ArrayList();
List<int> list = new List<int>();
arrayList.Add(1);
arrayList.Add("String");
arrayList.Add(new object());
list.Add(1);
list.Add("String"); // Compile-time Error
list.Add(new object()); // Compile-time Error
请阅读微软官方文档:https://blogs.msdn.microsoft.com/kcwalina/2005/09/23/system-collections-vs-system-collection-generic-and-system-collections-objectmodel/
注意:在理解它们的区别之前,您应该了解泛型:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/
使用List<T>可以防止强制转换错误。它对于避免运行时强制转换错误非常有用。
例子:
在这里(使用ArrayList),您可以编译这段代码,但稍后会看到一个执行错误。
ArrayList array1 = new ArrayList();
array1.Add(1);
array1.Add("Pony"); //No error at compile process
int total = 0;
foreach (int num in array1)
{
total += num; //-->Runtime Error
}
如果使用List,可以避免以下错误:
List<int> list1 = new List<int>();
list1.Add(1);
//list1.Add("Pony"); //<-- Error at compile process
int total = 0;
foreach (int num in list1 )
{
total += num;
}
参考: MSDN