泛型的好处是什么,什么时候用对于狠多童鞋还有些不清不楚
讲白了其实很简单,少花钱、办好事
我们来看看官方解释吧,不免俗的来看看ArrayList和List<T>
泛型类和泛型方法同时具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。泛型通常用与集合以及作用于集合的方法一起使用。
ArrayList是一个会强行对集合内元素进行装箱操作的对象(不知道装拆箱的自动面墙去,面完了去google),进行大量集合操作时效率低下,且不安全
System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
list.Add(3);
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining in Redmond.");
int t = 0;
// This causes an InvalidCastException to be returned.
foreach (int x in list)
{
t += x;
}
以上代码效率低下且因为没有类型检查会出错,而且要直到编译时才会报错
使用泛型后代码如下
// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();
// 没有装箱操作了:
list1.Add(3);
list1.Add("It is raining in Redmond.");//现在这行不需要编译就会提示错误