基本上,泛型集合在编译时是类型安全的:您指定集合应包含哪种类型的对象,类型系统将确保您只将这种对象放入其中.此外,当你拿出它时,你不需要施放物品.
举个例子,假设我们想要一个字符串集合.我们可以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];
Run Code Online (Sandbox Code Playgroud)
但是a 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];
Run Code Online (Sandbox Code Playgroud)
请注意,泛型集合只是泛型的更一般特性的一个示例(尽管是最常用的集合),它允许您根据其处理的数据类型来参数化类型或方法.