泛型委托
代码是C#红皮书第六版上看书的
代码
public interface IAccount
{
decimal Balance { get; }
string Name { 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 Algorithe
{
//2个泛型委托
public delegate Y Action<T, Y>(T t, Y u);
public delegate bool Predicate<T>(T input);
//Where T : IAccount...泛型约束,因为方法里使用了该接口的属性
//第一个参数:实现了IEnumerable<T>接口的类,以便Foreach
//第二三个参数,上面2个委托类型的方法
public static Y Acculateb<T, Y>(IEnumerable<T> col, Action<T, Y> action, Predicate<T> match)
where T : IAccount
{
Y sum = default(Y);
foreach (T input in col)
{
//使用委托方法
if (match(input))
{
//使用委托方法
sum = action(input, sum);
}
}
return sum;
}
}
class Program
{
static void Main(string[] args)
{
List<Account> list = new List<Account>();
list.Add(new Account("wht", 1));
list.Add(new Account("my", 2));
//2个委托参数都用Lamda表达式,很方便
decimal aa = Algorithe.Acculateb<Account, decimal>(list, (a, b) => a.Balance + b, f => f.Name == "wht");
//测试
Console.WriteLine(aa);
Console.Read();
}
}
{
decimal Balance { get; }
string Name { 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 Algorithe
{
//2个泛型委托
public delegate Y Action<T, Y>(T t, Y u);
public delegate bool Predicate<T>(T input);
//Where T : IAccount...泛型约束,因为方法里使用了该接口的属性
//第一个参数:实现了IEnumerable<T>接口的类,以便Foreach
//第二三个参数,上面2个委托类型的方法
public static Y Acculateb<T, Y>(IEnumerable<T> col, Action<T, Y> action, Predicate<T> match)
where T : IAccount
{
Y sum = default(Y);
foreach (T input in col)
{
//使用委托方法
if (match(input))
{
//使用委托方法
sum = action(input, sum);
}
}
return sum;
}
}
class Program
{
static void Main(string[] args)
{
List<Account> list = new List<Account>();
list.Add(new Account("wht", 1));
list.Add(new Account("my", 2));
//2个委托参数都用Lamda表达式,很方便
decimal aa = Algorithe.Acculateb<Account, decimal>(list, (a, b) => a.Balance + b, f => f.Name == "wht");
//测试
Console.WriteLine(aa);
Console.Read();
}
}