泛型(generic)是C#语言2.0和通用语言运行时(CLR)的一个新特性。泛型为.NET框架引入了类型参数(type parameters)的概念。
类型参数使得设计类和方法时,不必确定一个或多个具体参数,具体参数可延迟到客户代码中声明、实现。这意
味着使用泛型的类型参数T,写一个类MyList<T>,客户代码可以这样调用:MyList<int>, MyList<string>或
MyList<MyClass>。这避免了运行时类型转换或装箱操作的代价和风险。
例如,通过使用泛型类型参数 T,您可以编写其他客户端代码能够使用的单个类,而不致引入运行时强制转换或装箱操作的成本或风险。
// Declare the generic class.
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int.
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type string.
GenericList<string> list2 = new GenericList<string>();
// Declare a list of type ExampleClass.
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
-
使用泛型类型可以最大限度地重用代码、保护类型的安全以及提高性能。
-
泛型最常见的用途是创建集合类。
-
.NET Framework 类库在 System.Collections.Generic 命名空间中包含几个新的泛型集合类。 应尽可能地使用这些类来代替普通的类,如 System.Collections 命名空间中的 ArrayList。
-
您可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。
-
可以对泛型类进行约束以访问特定数据类型的方法。
-
关于泛型数据类型中使用的类型的信息可在运行时通过使用反射获取。