微软官方定义:c#2.0版语言和公共语言运行时(CLR)中添加了泛型。泛型将类型参数的概念引入。NET Framework中,泛型使设计类和方法成为可能
1.泛型简单示例
public class List<T>{ }
其中,T就是System,Collections.Generic.List<T>实例所存储类型的占位符,当定义泛型类的实例时,必须指定这个实例所存储的实力类型
List<string> list=new List<string>();
泛型允许程序员将一个实际的数据类型规约延迟至实例创建这个泛型的时候才确定;
泛型优点:编译时可以保证类型的安全;不用做类型转换,获得一定的性能提升
2.泛型方法 泛型委托 泛型接口
//泛型委托
public delegate void Del<T>(T item);
public static void Notify(int i) { };
Del<int> m1=new Del<int>(Notify);
//泛型接口
inteface MyInteface<T1,T2,T3> { T1 Method1 (T2 param1,T3 param2); } public class MyClass<T1,T2,T3>:MyInteface<T1,T2,T3> { public T1 Meehod1(T2 param1,T4 param2) { { throw; } } }
//泛型方法
static void Swap<T>(ref T T1,ref T T2) { T temp=t1;t1=t2;t2=temp;} public void Interactive() { string str1="a"; string str2="b"; Swap<string>(ref str1,ref str2); Console.WriteLine(str1+","+str2); }
3.泛型约束(constraints)
泛型约束表示可以给泛型的类型参数上加上约束,要求这些类型参数满足一定的条件
泛型的类型参数 约束 说明 where T :struct 类型参数需是值类型 where T :class 类型参数需是引用类型 where T:<base class name> 类型参数要派生自某个基类 where T:<interface name> 类型参数要实现某个接口 where T:U T和U都是类型参数,T必须是或者派生自U where T:new() 类型参数要有一个public的无参构造函数