这两天,看了一下webcast上面泛型编程的视频以及MSDN上面关于泛型的前四节内容,有一些感受和认识。
泛型是C#2.0和公共语言运行库(CLR)所增加的概念。所谓泛型,就是通过类型参数实现在同一份代码上操作多种数据类型。类型参数使得设计如下类和方法成为可能:这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。泛型编程实际上是一种编程范式,它利用"参数化类型"将参数类型化,从而实现代码更为更为灵活的复用。
泛型最常见的用途是创建集合类。.NET Framework 类库在 System.Collections.Generic 命名空间中包含几个新的泛型集合类。
泛型的两个最大的优点是能够消除通用化过程中类型与通用基类型之间的强制转化以及装箱和拆箱操作,还有就是编译时能够进行类型的检查。在对大型集合进行循环访问的时候,强制转化以及装箱和拆箱操作对性能的影响是明显的。比如下面使用非泛型集合类ArrayList创建它的两个实例,分别用来存储值类型和引用类型的数据。
System.Collections.ArrayList list1 = new System.Collections.ArrayList();
list1.Add(3);
list1.Add(105);
System.Collections.ArrayList list2 = new System.Collections.ArrayList(); l
ist2.Add("It is raining in Redmond.");
list2.Add("It is snowing in the mountains.");
虽然ArrayList 是一个使用起来非常方便的集合类,无需进行修改即可用来存储任何引用或值类型,但这种方便是需要付出代价的。添加到 ArrayList 中的任何引用或值类型都将隐式地向上强制转换为 Object。如果项是值类型,则必须在将其添加到列表中时进行装箱操作,在检索时进行取消装箱操作。并且缺少编译时的类型检查:因为 ArrayList 会将所有项都强制转换为 Object,所以在编译时无法防止客户端代码执行类似如下的操作:
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>();
// No boxing, no casting:
list1.Add(3);
List<string>list2 = new List<string>();
list2.Add("It is raining in Redmond”);