C#中有个叫做“泛型”的东西,就是说只是个壳,到底是int,string,bool还是什么类型,不知道,所以我们用个“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
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type
GenericList<string> list2 = new GenericList<string>();
// Declare a list of type
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
就是说定义了一个方法适用于很多类型的,泛型的作用就是重用代码、保护类型的安全以及提高性能。
可以定义泛型接口,泛型方法,泛型类,泛型委托,泛型事件。