C# 中的 ArrayList 与 List<>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2309694/
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-07 01:17:42  来源:igfitidea点击:

ArrayList vs List<> in C#

c#.netlistgenericsarraylist

提问by scatman

What is the difference between ArrayListand List<>in C#?

在 C# 中ArrayListList<>在 C# 中有什么区别?

Is it only that List<>has a type while ArrayListdoesn't?

是否只有List<>一个类型而ArrayList没有?

采纳答案by Mehrdad Afshari

Yes, pretty much. List<T>is a generic class. It supports storing values of a specific type without casting to or from object(which would have incurred boxing/unboxing overhead when Tis a value type in the ArrayListcase). ArrayListsimply stores objectreferences. As a generic collection, List<T>implements the generic IEnumerable<T>interface and can be used easily in LINQ (without requiring any Castor OfTypecall).

是的,差不多。List<T>是一个泛型类。它支持存储特定类型的值而无需进行强制转换object(如果T是值类型,则会产生装箱/拆箱开销ArrayList)。ArrayList只存储object引用。作为泛型集合,List<T>实现了泛型IEnumerable<T>接口,可以在 LINQ 中轻松使用(不需要任何CastOfType调用)。

ArrayListbelongs to the days that C# didn't have generics. It's deprecated in favor of List<T>. You shouldn't use ArrayListin new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.

ArrayList属于 C# 没有泛型的时代。它已被弃用,以支持List<T>. 您不应ArrayList在针对 .NET >= 2.0 的新代码中使用,除非您必须与使用它的旧 API 进行交互。

回答by Law Kant Dayal

ArrayListis the collections of different types data whereas List<>is the collection of similar type of its own depedencties.

ArrayList是不同类型数据List<>的集合,而是其自身依赖项的相似类型的集合。

回答by termas

Using List<T>you can prevent casting errors. It is very useful to avoid a runtimecasting error.

使用List<T>你可以防止铸造错误。避免运行时转换错误非常有用。

Example:

例子:

Here (using ArrayList) you can compile this code but you will see an execution error later.

在这里(使用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
}

If you use List, you avoid these errors:

如果使用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;
}

Reference: MSDN

参考: MSDN

回答by Anoop

To add to the above points. Using ArrayListin 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T>will use much low memory than the ArrayList.

补充以上几点。使用ArrayList在64位操作系统花费的时间比使用32位操作系统的2倍的内存。同时,通用列表List<T>将使用比ArrayList.

for example if we use a ArrayListof 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int>of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.

例如,如果我们ArrayList在 32 位中使用19MB,那么在 64 位中将需要 39MB。但是如果你有一个List<int>32 位的 8MB通用列表,那么它在 64 位中只需要 8.1MB,与 ArrayList 相比,这是一个惊人的 481% 差异。

Source: ArrayList's vs. generic List for primitive types and 64-bits

来源:ArrayList 与基本类型和 64 位的泛型列表

回答by user1998271

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.

对我来说,这一切都与了解您的数据有关。如果我继续在效率的基础上扩展我的代码,我将不得不选择 List 选项作为破译我的数据的一种方式,而无需总是想知道类型,尤其是“自定义类型”的不必要步骤。如果机器理解差异并且可以确定它是我实际处理的数据类型,那么我为什么要妨碍并浪费时间通过“IF THEN ELSE”确定的旋转?我的理念是让机器为我工作,而不是让我在机器上工作?了解不同目标代码命令的独特差异对提高代码效率大有帮助。

Tom Johnson (One Entry ... One Exit)

汤姆约翰逊(一进一出)

回答by Deepak

Using "List" you can prevent casting errors. It is very useful to avoid a runtime casting error.

使用“列表”可以防止铸造错误。避免运行时转换错误非常有用。

Example:

例子:

Here (using ArrayList) you can compile this code but you will see an execution error later.

在这里(使用 ArrayList)您可以编译此代码,但稍后您将看到执行错误。

    // Create a new ArrayList


    System.Collections.ArrayList mixedList = new System.Collections.ArrayList();


    // Add some numbers to the list
    mixedList.Add(7);
    mixedList.Add(21);


    // Add some strings to the list
    mixedList.Add("Hello");
    mixedList.Add("This is going to be a problem");




    System.Collections.ArrayList intList = new System.Collections.ArrayList();
    System.Collections.ArrayList strList = new System.Collections.ArrayList();


    foreach (object obj in mixedList)
    {
        if (obj.GetType().Equals(typeof(int)))
        {
            intList.Add(obj);
        }
        else if (obj.GetType().Equals(typeof(string)))
        {
            strList.Add(obj);
        }
        else
        {
            // error.
        }
    }

回答by NullReference

Another difference to add is with respect to Thread Synchronization.

要添加的另一个不同之处在于线程同步。

ArrayListprovides 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.

ArrayList通过 Synchronized 属性提供一些线程安全性,它返回一个围绕集合的线程安全包装器。包装器的工作原理是在每次添加或删除操作时锁定整个集合。因此,试图访问集合的每个线程都必须等待轮到它来获取一个锁。这是不可扩展的,并且可能导致大型集合的性能显着下降。

List<T>不提供任何线程同步;当在多个线程上同时添加或删除项目时,用户代码必须提供所有同步。

More info here Thread Synchronization in the .Net Framework

更多信息请参阅 .Net Framework 中的线程同步

回答by Hassan Rahman

ArrayListare not type safe whereas List<T>are type safe. Simple :).

ArrayList不是类型安全的,而List<T>类型安全。简单的 :)。

回答by burzhuy

I think, the differences between ArrayListand List<T>are:

我认为,之间的差别ArrayListList<T>有:

  1. List<T>, where T is value-type is faster than ArrayList. This is because List<T>avoids boxing/unboxing (where T is value-type).
  2. Many sources say - usually ArrayListused just for backward compatibility. (is not a real difference, but i think it is important note).
  3. Reflection is easier with nongeneric ArrayListthen List<T>
  4. ArrayListhas IsSynchronizedproperty. So, It is easy to create and use syncronised ArrayList. I didin't found IsSynchronizedproperty for List<T>. Also Keep in mind this type of synchronization is relatively inefficient, msdn):

    var arraylist = new ArrayList();
    var arrayListSyncronized = ArrayList.Synchronized(arraylist
    Console.WriteLine($"syncronized {arraylist.IsSynchronized}");
    Console.WriteLine($"syncronized {arrayListSyncronized.IsSynchronized}");
    
    var list = new List<object>();
    var listSyncronized = ArrayList.Synchronized(list);
    Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
    Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
    
  5. ArrayListhas ArrayList.SyncRootproperty which can be used for syncronisation (msdn). List<T>hasn't SyncRootproperty, so in the following construction you need to use some object if you use List<T>:

    ArrayList myCollection = new ArrayList();
    lock(myCollection.SyncRoot) //  ofcourse you can use another object for this goal
    {
        foreach (object item in myCollection)
        {
            // ...
        }
    }
    
  1. List<T>,其中 T 是值类型比 快ArrayList。这是因为List<T>避免装箱/拆箱(其中 T 是值类型)。
  2. 许多消息来源说 - 通常ArrayList仅用于向后兼容。(不是真正的区别,但我认为这是重要的注意事项)。
  3. 反思是与非泛型容易ArrayListList<T>
  4. ArrayList拥有IsSynchronized财产。因此,很容易创建和使用同步ArrayList. 我didin't发现IsSynchronized财产List<T>。另外请记住,这种类型的同步效率相对较低,msdn):

    var arraylist = new ArrayList();
    var arrayListSyncronized = ArrayList.Synchronized(arraylist
    Console.WriteLine($"syncronized {arraylist.IsSynchronized}");
    Console.WriteLine($"syncronized {arrayListSyncronized.IsSynchronized}");
    
    var list = new List<object>();
    var listSyncronized = ArrayList.Synchronized(list);
    Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
    Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
    
  5. ArrayList具有ArrayList.SyncRoot可用于同步的属性 ( msdn)。List<T>没有SyncRoot属性,因此在以下构造中,如果使用,则需要使用某个对象List<T>

    ArrayList myCollection = new ArrayList();
    lock(myCollection.SyncRoot) //  ofcourse you can use another object for this goal
    {
        foreach (object item in myCollection)
        {
            // ...
        }
    }
    

回答by Aravin

Simple Answer is,

简单的答案是,

ArrayList is Non-Generic

ArrayList 是非泛型的

  • It is an Object Type, so you can store any data type into it.
  • You can store any values (value type or reference type) such string, int, employee and object in the ArrayList. (Note and)
  • Boxing and Unboxing will happen.
  • Not type safe.
  • It is older.
  • 它是一种对象类型,因此您可以将任何数据类型存储到其中。
  • 您可以在 ArrayList 中存储任何值(值类型或引用类型),例如 string、int、employee 和 object。(注和)
  • 装箱和拆箱将发生。
  • 不是类型安全的。
  • 它更老了。

List is Generic

列表是通用的

  • It is a Type of Type, so you can specify the T on run-time.
  • You can store an only value of Type T (string or int or employee or object) based on the declaration. (Note or)
  • Boxing and Unboxing will not happen.
  • Type safe.
  • It is newer.
  • 它是 Type 的类型,因此您可以在运行时指定 T。
  • 您可以根据声明仅存储类型 T(字符串或整数或员工或对象)的值。(注或)
  • 装箱和拆箱不会发生。
  • 键入安全。
  • 它较新。

Example:

例子:

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

Please read the Microsoft official document: https://blogs.msdn.microsoft.com/kcwalina/2005/09/23/system-collections-vs-system-collection-generic-and-system-collections-objectmodel/

请阅读微软官方文档https: //blogs.msdn.microsoft.com/kcwalina/2005/09/23/system-collections-vs-system-collection-generic-and-system-collections-objectmodel/

enter image description here

在此处输入图片说明

Note: You should know Generics before understanding the difference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

注意:在理解差异之前,您应该了解泛型:https: //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/