C# 泛型方法示例

 1 using System;
 2 using System.Collections.Generic;
 3 
 4 namespace ConsoleApplication2
 5 {
 6     public class Account
 7     {
 8         public string Name { get; private set; }
 9         public decimal Balance { get; private set; }
10         public Account(string name, decimal balance)
11         {
12             this.Name = name;
13             this.Balance = balance;
14         }
15     }
16 
17     public static class Algorithm
18     {
19         public static decimal AccumulateSimple(IEnumerable<Account> source)
20         {
21             decimal sum = 0;
22             foreach (Account a in source)
23             {
24                 sum += a.Balance;
25             }
26             return sum;
27         }
28     }
29 
30     class Program
31     {
32         static void Main(string[] args)
33         {
34             var accounts = new List<Account>()
35             {
36                 new Account("Christian", 1500),
37                 new Account("Stephanie", 2200),
38                 new Account("Angela", 1800)
39             };
40 
41             decimal amount = Algorithm.AccumulateSimple(accounts);
42             Console.WriteLine("合计:{0}", amount);
43             Console.ReadKey();
44         }
45     }
46 }

 上面的代码只能用于Account对象,使用泛型方法就可以避免这个问题。(带约束的泛型方法)

 1 using System;
 2 using System.Collections.Generic;
 3 
 4 namespace ConsoleApplication1
 5 {
 6     public interface IAccount
 7     {
 8         decimal Balance { get; }
 9         string Name { get; }
10     }
11 
12     public class Account : IAccount
13     {
14         public decimal Balance { get; private set; }
15         public string Name { get; private set; }
16         public Account(string name, decimal balance)
17         {
18             this.Name = name;
19             this.Balance = balance;
20         }
21     }
22 
23     public static class Algorithm
24     {
25         public static decimal Accumulate<TAccount>(IEnumerable<TAccount> source)
26         where TAccount : IAccount
27         {
28             decimal sum = 0;
29             foreach (TAccount a in source)
30             {
31                 sum += a.Balance;
32             }
33             return sum;
34         }
35     }
36     class Program
37     {
38         static void Main(string[] args)
39         {
40             var accounts = new List<Account>()
41             {
42                 new Account("Christian", 1500),
43                 new Account("Stephanie", 220000),
44                 new Account("Angela", 1800)
45             };
46 
47             decimal amount = Algorithm.Accumulate<Account>(accounts);
48 
49             Console.WriteLine("合计:{0}", amount);
50             Console.ReadKey();
51         }
52     }
53 }

 

posted @ 2014-04-15 10:59  海阔天空XM  阅读(424)  评论(0编辑  收藏  举报