- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Collections;
- namespace Generic_Method
- {
- /*
- //-------第一种方案--普通方法---------
- 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.balance = balance;
- this.name = name;
- }
- }
- public static class Algorithm
- {
- //面对接口编程,只要参数实现了IEnumerable接口就行;
- //比如Main函数里的List<Account> accounts;
- 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("a", 1500));
- accounts.Add(new Account("b", 2000));
- accounts.Add(new Account("c", 2500));
- decimal amount = Algorithm.AccumulateSimple(accounts);
- Console.WriteLine(amount);
- }
- }
- */
- //-------第二种方案--使用泛型编码---------
- 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.balance = balance;
- this.name = name;
- }
- }
- public static class Algorithm
- {
- //面对接口编程,只要参数实现了IEnumerable接口就行;
- //比如Main函数里的List<Account> accounts;
- //where 子句可以用于泛型类也可以用于泛型方法
- public static decimal AccumulateSimple<TAccount> (IEnumerable<TAccount> coll)
- where TAccount:IAccount
- {
- decimal sum = 0;
- foreach (TAccount a in coll)
- {
- sum += a.Balance;
- }
- return sum;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- List<Account> accounts = new List<Account>();
- accounts.Add(new Account("a", 1500));
- accounts.Add(new Account("b", 2000));
- accounts.Add(new Account("c", 2500));
- decimal amount = Algorithm.AccumulateSimple(accounts);
- Console.WriteLine(amount);
- }
- }
- }