除了定义泛型类之外,还可以定义泛型方法。在泛型方法中,泛型类型用方法声明来定义。
Swap<T>方法把T定义为泛型类型,用于两个参数和一个变量temp:
void Swap<T>(ref T x, ref T y)
{
T temp;
temp = x;
x = y;
y = temp;
}
把泛型类型赋予方法调用,就可以调用泛型方法:
int i = 4;
int j = 5;
Swap<int>(ref i, ref j);
但是,因为C#编译器会通过调用Swap方法来获取参数的类型,所以不需要把泛型类型赋予方法调用。泛型方法可以像非泛型方法那样调用:
int i = 4;
int j = 5;
Swap(ref i, ref j);
下面的例子使用泛型方法累加集合中的所有元素。为了说明泛型方法的功能,下面的Account类包含name和balance:
public class Account
{
private string name;
public string Name
{
get
{
return name;
}
}
private decimal balance;
public decimal Balance
{
get
{
return balance;
}
}
public Account(string name, Decimal balance)
{
this.name = name;
this.balance = balance;
}
}
应累加结余的所有账目操作都添加到List<Account>类型的账目列表中:
List<Account> accounts = new List<Account>();
accounts.Add(new Account("Christian", 1500));
accounts.Add(new Account("Sharon", 2200));
accounts.Add(new Account("Katie", 1800));
累加所有Account对象的传统方式是用foreach语句迭代所有的Account对象,如下所示。foreach语句使用IEnumerable接口迭代集合的元素,所以AccumulateSimple()方法的参数是IEnumerable类型。这样,AccumulateSimple()方法就可以用于所有实现IEnumerable接口的集合类。在这个方法的实现代码中,直接访问Account对象的Balance属性:
public static class Algorithm
{
public static decimal AccumulateSimple(IEnumerable e)
{
decimal sum = 0;
foreach (Account a in e)
{
sum += a.Balance;
}
return sum;
}
}
Accumulate()方法的调用方式如下:
decimal amount = Algorithm.AccumulateSimple(accounts);
第一个实现代码的问题是,它只能用于Account对象。使用泛型方法就可以避免这个问题。
Accumulate()方法的第二个版本接受实现了IAccount接口的任意类型。如前面的泛型类所述,泛型类型可以用where子句来限制。这个子句也可以用于泛型方法。Accumulate()方法的参数改为IEnumerable<T>。IEnumerable<T>是IEnumerable接口的泛型版本,由泛型集合类实现。
public static decimal Accumulate<TAccount>(IEnumerable<TAccount> coll)
where TAccount : IAccount
{
decimal sum = 0;
foreach (TAccount a in coll)
{
sum += a.Balance;
}
return sum;
}
将Account类型定义为泛型类型参数,就可以调用新的Accumulate()方法:
decimal amount = Algorithm.Accumulate<Account>(accounts);
因为编译器会从方法的参数类型中自动推断出泛型类型参数,所以以如下方式调用Accumulate()方法是有效的:
decimal amount = Algorithm.Accumulate(accounts);
泛型类型实现IAccount接口的要求过于严厉。这个要求可以使用泛型委托来改变。在下一节中,Accumulate()方法将改为独立于任何接口。