泛型(Generic) 允许您延迟编写类或方法中的编程元素的数据类型的规范,直到实际在程序中使用它的时候。换句话说,泛型允许您编写一个可以与任何数据类型一起工作的类或方法。
泛型类
类中定义泛型具体格式如下:
class DemoList<T>{
T[] arr;
public DemoList(int capcity){
arr=new T[int capcity]
}
public T this[int index]{
get{
return arr[index];
}
}
}
static void Main()
{
DemoList<string> arr=new DemoList<string>(10);//在实例化对象时确定T的类型为string,那该类中所有用T表示的类型都是string;
}
方法中定义泛型:
class Demo{
public T[] getArray<T>(int count){
return new T[count];
}
}
static void Main(){
Demo d=new Demo();
int[] arr=d.getArray<int>(10);//如上,在调用方法时必须确定泛型的类型,这里T的类型为int,所以该方法中所有用T表示的类型都为int;
}
同样的,还有泛型委托、泛型接口、泛型集合,使用和泛型类泛型方法大同小异,这里就不详细说了,最后说一种约束,叫泛型约束
下面举一个例子:
class MyClass<U>where U : struct///约束U参数必须为“值 类型”
{
}
public void MyMetod<T>(T t)where T : struct
{
}