- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace 泛型方法
- {
- class Program
- {
- public interface IAccount
- {
- decimal Balance { get;}
- }
- public class Account : IAccount
- {
- private string mName;
- public string Name
- {
- get
- {
- return mName;
- }
- set
- {
- mName = value;
- }
- }
- private decimal mBalance;
- public decimal Balance
- {
- get
- {
- return mBalance;
- }
- set
- {
- mBalance = value;
- }
- }
- public Account(string name, decimal balance)
- {
- this.mName = name;
- this.mBalance = balance;
- }
- }
- public static class Algorithm
- {
- public static decimal Accoumulate<TAccount>(IEnumerable<TAccount> coll) where TAccount : IAccount
- {
- decimal sum = 0;
- foreach (TAccount account in coll)
- {
- sum += account.Balance;
- }
- return sum;
- }
- }
- static void Main(string[] args)
- {
- List<Account> Accounts = new List<Account>();
- Accounts.Add(new Account("",1500));
- Accounts.Add(new Account("",1500));
- Accounts.Add(new Account("",1500));
- Accounts.Add(new Account("",1500));
- Accounts.Add(new Account("",1500));
- Console.WriteLine(Algorithm.Accoumulate<Account>(Accounts));
- Console.ReadLine();
- }
- }
- }
《C# 2005 & .Net3.0 高级编程第5版》