C#泛型基本概念

**

泛型(Generic)

**
允许您延迟编写类或方法中的编程元素的数据类型的规范,直到实际在程序中使用它的时候。换句话说,泛型允许您编写一个可以与任何数据类型一起工作的类或方法。
类中定义泛型具体格式如下:

class DemoList<T>{
T[] arr;
public DemoList(int capcity){ 
      arr=new T[int capcity]
}
public T this[int index]{ get{
      return arr[index];
}
}
}
Main:
DemoList<string> arr=new DemoList<string>(10);

如上,在实例化对象时确定T的类型为string,那该类中所有用T表示的类型都是string;

方法中定义泛型:

 class Demo{
public T[] getArray<T>(int count){ 
       return new T[count];
}
}

Main:
Demo d=new Demo();
int[] arr=d.getArray<int>(10);

如上,在调用方法时必须确定泛型的类型,这里T的类型为int,所以该方法中所有用T表示的类型都为int;

猜你喜欢

转载自blog.csdn.net/qq_42485607/article/details/81033756