泛型方法的简介
C#泛型机制只支持“在方法声明上包含类型参数” -- 即泛型方法。
C#泛型机制不支持在除方法外的其他成员(包括属性、事件、索引器、构造器、析构器)的声明上包含类型参数,但这些成员本身可以包含在泛型类型中,并使用泛型类型的类型参数。
泛型方法既可以包含在泛型类型中,也可以包含在非泛型类型中。
泛型方法的声明与调用
public class Finder
{
// 泛型方法的声明
public static int Find(T[] items,T item)
{
for(int i=0; i
{
if(items[i].Equals(item)
{
return i;
}
}
return -1;
}
}
// 泛型方法的调用
int i = Finder.Find(new int[]{1,3,4,5,6,8,9},6);泛型编程
泛型方法的重载
class MyClass
{
void F1(T[] a,int i); // 不可以构成重载方法
void F1(U[] a,int i);
void F2(int x); // 可以构成重载方法
void F2(int x);
void F3(T t) where T : A; // 不可以构成重载方法
void F3(T t) where T : B;
}泛型方法的重写
abstract class Base
{
public abstract T F(T t,U u) where U : T;
public abstract T G(T t) where U : IComparable;
}
class Derived:Base
{
// 合法的重写,约束被默认继承
public override X F(X,Y)(X x,Y y){}
// 非法的重写,指定任何约束都是多余的
public override T G(T t) where T : Comparable{}
}