回答(11)
2 years ago
是的,差不多 . List 是一个通用类 . 它支持存储特定类型的值而无需转换为 object (当 T 是 ArrayList 情况下的值类型时,会产生装箱/拆箱开销) . ArrayList 只存储 object 引用 . 作为通用集合, List 实现了通用 IEnumerable 接口,可以在LINQ中轻松使用(无需任何 Cast 或 OfType 调用) .
ArrayList 属于C#不赞成't have generics. It'的日子,赞成 List . 您不应该在面向.NET> = 2.0的新代码中使用 ArrayList ,除非您必须与使用它的旧API进行交互 .
2 years ago
使用 List 可以防止出现错误 . 避免运行时转换错误非常有用 .
例:
在这里(使用 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 list1 = new List();
list1.Add(1);
//list1.Add("Pony"); //
int total = 0;
foreach (int num in list1 )
{
total += num;
}