【发布时间】:2010-12-21 14:47:18
【问题描述】:
【问题讨论】:
-
既然有勺子,为什么还要用叉子? ;-)
-
我更喜欢张开的:lesjones.com/www/images/posts/…
【问题讨论】:
使用通用列表而不是 ArrayList 的方法之一是 ArrayList 接受任何类型的对象,如果您打算只存储给定类型的对象,这可能会导致运行时错误,而这些错误不会发生泛型。
例子:
var numbers=new ArrayList();
numbers.Add(1);
numbers.Add("abcd"); //This will compile!
int theNumber=(int)numbers[1]; //This will cause an exception
使用泛型列表时,请确保列表中仅存储所需的类型:
var numbers=new List<int>();
numbers.Add(1);
numbers.Add("abcd"); //This will NOT compile
【讨论】:
一个简单的解释。
当您有一个整数列表时,您只想确保程序的某些部分将一个字符串添加到其中。使用泛型,您告诉编译器您决定在列表中只包含整数(或任何类型),并确保您不会违反自己的法律。
您可以说,它是另一种语言(和运行时)功能,可以在代码中表达您的意图。这使工具能够为您提供支持。
【讨论】:
根据 Konamiman 和 Stefan 的回答,在处理值类型时使用泛型集合也可以避免装箱/拆箱的成本。
每次将值类型添加到非泛型集合时,都需要将其装箱,然后在将其从集合中删除时将其拆箱(假设您想做任何特定于类型的操作和它)。
ArrayList myList = new ArrayList();
myList.Add(42); // box
myList.Add(DateTime.Now) // box
myList.Add(3.14) // box
int x = (int)myList[0]; // unbox
DateTime y = (DateTime)myList[1]; // unbox
double z = (double)myList[2]; // unbox
【讨论】:
正如之前的海报所说,使用泛型集合存在编译时安全问题;他们可以在编译时发现一些愚蠢的错误(这比在运行时更好)。
不过,还有一些其他原因更喜欢它们:
List<int> 存储的等效方法慢。例如:
object x = "5";
var intlist = new List<int>();
intlist.Add((int)x); //fails early; compiler requires this cast
//...perhaps much later...
foreach(int num in intlist)...
var arraylist = new ArrayList();
arraylist.Add(x); //this is OK though a cast would be advisable
//...perhaps much later...
foreach(int num in arraylist) ... //fails late
后期故障比早期故障更难调试,因为检测到故障的点已从原始编码错误中进一步消除。
【讨论】: