在C#中,ArrayList和List<>的区别
在C#中,ArrayList和List<>的区别
在 C# 中,ArrayList
和 List<>
有什么区别?
仅仅是 List<>
有类型而 ArrayList
没有吗?
admin 更改状态以发布 2023年5月23日
使用 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
,可以避免这些错误:
Listlist1 = new List (); list1.Add(1); //list1.Add("Pony"); //<-- Error at compile process int total = 0; foreach (int num in list1 ) { total += num; }
参考链接:
MSDN