-
-
namespace GenericMethodDemo
-
{
-
using System;
-
using System.Collections;
-
using System.Collections.Generic;
-
-
public interface IAccount
-
{
-
string Name { get; }
-
decimal Balance { get; }
-
}
-
-
public class Account : IAccount
-
{
-
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;
-
}
-
}
-
-
public static class Algorithm
-
{
-
//一般的方法【参数为继承IEnumerable接口的类】
-
public static decimal AccumulateSimple(IEnumerable e)
-
{
-
decimal sum = 0;
-
-
foreach (Account a in e)
-
{
-
sum += a.Balance;
-
}//这里使用Account显示出一定局限性
-
-
return sum;
-
}
-
-
//一般的泛型方法【参数为继承IEnumerable<T>泛型接口的类】
-
public static decimal Accumulate<T>(IEnumerable<T> coll)
-
where T : IAccount//接口约束--任然显示出一定得局限性,下面使用委托可以克服这种局限
-
{
-
decimal sum = 0;
-
-
foreach (T a in coll)
-
{
-
sum += a.Balance;
-
}
-
-
return sum;
-
}
-
-
//泛型委托
-
public delegate U Adder<T, U>(T t, U u);
-
//使用泛型委托的泛型方法
-
public static U Accumulate<T, U>(IEnumerable<T> coll, Adder<T, U> adder)
-
{
-
U sum = default(U);//设置默认值
-
-
foreach (T a in coll)
-
{
-
sum = adder(a, sum);
-
}
-
-
return sum;
-
}
-
public static U AccumulateIf<T, U>(IEnumerable<T> coll, Adder<T, U> adder, Predicate<T> match)
-
{
-
U sum = default(U);
-
-
foreach (T a in coll)
-
{
-
if (match(a))
-
sum = adder(a, sum);
-
}
-
-
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));
-
-
//调用一般的方法
-
Console.WriteLine("sum of all accounts {0}", Algorithm.AccumulateSimple(accounts));
-
//调用一般的泛型方法
-
Console.WriteLine("sum of all accounts {0}", Algorithm.Accumulate<Account>(accounts));
-
//调用使用泛型委托的泛型方法
-
Console.WriteLine("sum of all accounts {0}",
-
Algorithm.Accumulate<Account, decimal>(accounts, delegate(Account a, decimal d) { return a.Balance + d; }));//使用匿名委托
-
Console.WriteLine("sum of all accounts {0}",
-
Algorithm.Accumulate<Account, decimal>(accounts, new Algorithm.Adder<Account, decimal>(AccountAdder)));//使用泛型委托
-
Console.WriteLine("sum of all accounts {0}",
-
Algorithm.Accumulate<Account, decimal>(accounts, AccountAdder));
-
-
Console.WriteLine(Algorithm.AccumulateIf<Account, decimal>(
-
accounts,
-
delegate(Account a, decimal d) { return a.Balance + d; },
-
delegate(Account a) { return a.Balance > 1800 ? true : false; }
-
));//使用匿名委托
-
-
Console.ReadLine();
-
}
-
-
//委托调用方法
-
static decimal AccountAdder(Account a, decimal d)
-
{
-
return a.Balance + d;
-
}
-
}
-
}