<分区>
Possible Duplicate:
What is cool about generics, why use them?
重复:
What is cool about generics, why use them?
我的基本问题与标题相同。但我想了解更多可以启发我了解 C# 泛型世界的东西。
谢谢! 阿卡什
<分区>
Possible Duplicate:
What is cool about generics, why use them?
重复:
What is cool about generics, why use them?
我的基本问题与标题相同。但我想了解更多可以启发我了解 C# 泛型世界的东西。
谢谢! 阿卡什
最佳答案
使用通用列表而不是 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
关于c# - 当我们可以在 ArrayList 中存储东西(值和引用)时,为什么还要使用泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1819300/