2010-08-20 64 views

回答

8

基本上,泛型集合在编译时是类型安全的:您指定集合应该包含哪种类型的对象,类型系统将确保您只将该类型的对象放入其中。而且,当你把它拿出来时,你不需要投射物品。

作为一个例子,假设我们想要一个字符串集合。我们可以使用ArrayList这样的:

ArrayList list = new ArrayList(); 
list.Add("hello"); 
list.Add(new Button()); // Oops! That's not meant to be there... 
... 
string firstEntry = (string) list[0]; 

List<string>将阻止无效项避免投:

List<string> list = new List<string>(); 
list.Add("hello"); 
list.Add(new Button()); // This won't compile 
... 
// No need for a cast; guaranteed to be type-safe... although it 
// will still throw an exception if the list is empty 
string firstEntry = list[0]; 

注意泛型集合只是一个例子(虽然是最常用的一个)泛型的更一般的特征,它允许你通过它处理的数据类型来参数化类型或方法。

1

ArrayList和HashTable类型包含在.Net 1.0中。它们或多或少等同于列表和字典。

它们都存在与2.0版本中的泛型引入之前保持与.Net 1.0或1.1中编写的代码的兼容性,如果您的目标是.Net 2.0或更高版本,通常应该避免这种情况。