泛型允许编写一个可以与任何数据类型一起工作的类或方法。当编译器遇到类的构造函数或方法的函数调用时,它会生成代码来处理指定的数据类型。通过下面的小例子就可以比较清楚的理解泛型编程了。
代码如下:
using System;
using System.Collections;
namespace ConsoleApplication1
{
//泛型编程
public class MyGeneric<T>
{
private T[] array;
public MyGeneric(int nSize)
{
array = new T[nSize + 1];
}
public T getItem(int nIndex)
{
return array[nIndex];
}
public void setItem(int nIndex,T t)
{
array[nIndex] = t;
}
}
class Entry
{
static void Main()
{
MyGeneric<int> myGeneric = new MyGeneric<int>(10);
for(int i = 0;i<10;i++)
{
myGeneric.setItem(i, i * 2);
Console.WriteLine("myGeneric[{0}] = {1}",i,myGeneric.getItem(i));
}
Console.ReadKey();
}
}
}
输出结果: