01—泛型概述


public interface ISessionChannel<TSession>
{
TSession Session{ get;}
}
interface 【接口名】<T>
{
【接口体】
}
声明泛型接口时,与声明一般接口的唯一区别是增加了一个<T>。一般来说,声明泛型接口与声明非泛型接口遵循相同的规则。泛型类型声明所实现的接口必须对所有可能的构造类型都保持唯一,否则就无法确定该为某些构造类型调用哪个方法。
//创建一个泛型接口
public interface IGenericInterface<T>
{
T CreateInstance(); //接口中调用 CreateInstance 方法
}
//实现上面泛型接口的泛型类
//派生约束 where T: TI(T 要继承自 TI)
//构造函数约束 where T:new()(T 可以实例化)
public class Factory<T,TI>;IGenericInterface<TI> where T: TI,new()
{
public TI CreateInstance() //创建一个公共方法 CreateInstance
{
return new T();
}
}
class Program
{
static void Main(string[] args)
{
//实例化接口
IGenericInterface<System.ComponentModel.IListSource> factory =
new Factory<System.Data.DataTable,System.ComponentModel.IListSource>();
//输出指定泛型的类型
Console.WriteLine(factory.CreateInstance().GetType().ToString());
Console.ReadLine();
}
}
程序的运行结果如图1 所示。
3. 泛型方法
泛型方法的声明形式如下:
【修饰符】 Void 【方法名】<类型参数T>
{
【方法体】
}
泛型方法是在声明中包括了类型参数T的方法。泛型方法可以在类、结构或接口声明中声明,这些类、结构或接口本身可以是泛型或非泛型。如果在泛型类型声明中声明泛型方法,则方法体可以同时引用该方法的类型参数T和包含该方法的声明的类型参数 T。
说明
泛型方法可以使用多类型参数进行重载。
【例4】 创建一个控制台应用程序,通过定义一个泛型方法来查找数组中某个数字的位置。
代码如下:
public class Finder //建立一个公共类 Finder
{
public static int Find<T>(T[] items,T item) //创建泛型方法
{
for(int i= 0;i < items.Length;i++) //调用 for 循环
{
if(items[i].Equals(item)) //调用 Equals 方法比较两个数
{
return i; //返回相等数在数组中的位置
}
}
return -1; //如果不存在指定的数,则返回-1
}
}
class Program
{
static void Main(string[] args)
{
int i= Finder.Find<int>(new int[](1,2,3,4,5,6,8,9),6); //调用泛型方法,并定义数组指定数字
Console.WriteLine("6 在数组中的位置:"+i.ToString()); //输出中数字在数组中的位置
Console.ReadLine();
}
}
程序的运行结果是“6 在数组中的位置为5”。