**
泛型(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;
本文介绍了泛型编程的概念及其在类和方法中的应用。通过具体的代码示例解释了如何定义和使用泛型类与方法,使读者能够理解泛型如何帮助编写更加灵活且可重用的代码。
884

被折叠的 条评论
为什么被折叠?



