ArrayList vs List<> in C#

后端 未结 12 1972
深忆病人
深忆病人 2020-11-22 04:10

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

Is it only that List<> has a type while ArrayLis

12条回答
  •  别跟我提以往
    2020-11-22 05:07

    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.

        // 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.
            }
        }
    

提交回复
热议问题