使用泛型可以定义接口,接口中的方法可以带泛型参数。
下面是一个泛型接口的例子:
public interface IComparable<T>
{
int CompareTo(T other);
}
对于一个Person类的实现:
public class Person : IComparable<Person>
{
public int CompareTo(Person obj)
{
return this.lastname.CompareTo(other.lastname);
}
}
除了定义泛型类型之外,还可以定义泛型方法。 在泛型方法中,泛型类型用方法声明来定义。
下面示例一个交换的泛型方法:
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);
下面的例子使用泛型方法累加集合中所有元素。
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace GenericMethod
{
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;
}
}
// 传统方法 使用foreach语句迭代所有的Account对象
public static class Algorithm
{
public static decimal AccumulateSimple(IEnumerable e)
{
decimal sum = 0;
foreach (Account a in e)
{
sum += a.Balance;
}
return sum;
}
}
class Program
{
static void Main(string[] args)
{
List<Account> accounts = new List<Account>();
accounts.Add(new Account("Christian", 1500));
accounts.Add(new Account("Sharon", 2200));
accounts.Add(new Account("Katie", 1800));
decimal amount = Algorithm.AccumulateSimple(accounts);
Console.WriteLine(amount.ToString());
Console.ReadLine();
}
}
}
当使用上面的传统方法的时候就会有一个问题, 它只能适用于Account对象
foreach (Account a in e)
将这个方法扩充到对所有对象适用的时候
// 加强版的泛型方法
public class Account : IAccount
{
//...
}
public interface IAccount
{
decimal Balance
{
get;
}
string Name
{
get;
}
}
public static class Algorithm
{
public static decimal AccumulateSimple<TAccount>(IEnumerable<TAccount> coll) where TAccount : IAccount
{
decimal sum = 0;
foreach (TAccount a in coll)
{
sum += a.Balance;
}
return sum;
}
}
调用可以采用2种方法来调用这个泛型方法了:
decimal amount = Algorithm.Accumulate<Account>(accounts);
或者:
decimal amount = Algorithm.Accmulate(accounts);