其中,泛型支持是C# 2.0的重中之重,.NET框架从CLR级别实现了对泛型的支持,提供专门的IL指令支持泛型操作,同时配合C#语言机制构造一种全新的编程结构,实现了对类型抽象化的通用处理方式,这就是算法重用。
以最简单的交换数据为例,我们来了解泛型带来的好处:
// Release : code01, 2009/05/07
// Author : Anytao, http://www.anytao.com
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
public static void Swap(ref string str1, ref string str2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
// Author : Anytao, http://www.anytao.com
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
public static void Swap(ref string str1, ref string str2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
以上两种算法分别实现了对整型、字符串型数据的交换,在泛型引入之前实现相同的交换算法需要分别为所有的类型构建相似的处理逻辑,这显然是一种代码上的浪费,而泛型特性彻底解决了这一问题:
// Release : code02, 2009/05/07
// Author : Anytao, http://www.anytao.com
public static void Swap<T>(ref T t1, ref T t2)
{
T temp = t1;
t1 = t2;
t2 = temp;
}
// Author : Anytao, http://www.anytao.com
public static void Swap<T>(ref T t1, ref T t2)
{
T temp = t1;
t1 = t2;
t2 = temp;
}
对于不同的类型,在运行时以实际类型对T占位符进行替换,并转换为本地代码,彻底实现了灵活的类型抽象和算法重用。同时,除了代码级别的重用好处,泛型解决了类型转换、装箱与拆箱、类型安全等诸多问题,为程序设计带来巨大的变革。