C#中泛型方法作用举例

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace 泛型
  7. {
  8.     class 泛型方法
  9.     {
  10.         public static void Main()
  11.         { 
  12.             //将所有账目加入到List集合中
  13.             List<Account> list = new List<Account>();
  14.             list.Add( new Account( "aladdin" , 1000 ) );
  15.             list.Add(new Account("zhaohaifu", 2000));
  16.             list.Add(new Account("jacky", 3000));
  17.             //计算总合
  18.             decimal total = Algorithm.AccumulateSimple( list );
  19.             Console.WriteLine( "账单总计:" + total );
  20.             Console.ReadLine();
  21.         }
  22.     }
  23.     //计算类
  24.     class Algorithm
  25.     {
  26.         public static decimal AccumulateSimple<TAccount>( IEnumerable<TAccount> e )
  27.             where TAccount : Account
  28.         { 
  29.             decimal redec = 0 ;
  30.             foreach( TAccount a in e )
  31.             {
  32.                 redec += a.Balance;
  33.             }
  34.             return redec;
  35.         }
  36.     }
  37.     //帐目类
  38.     class Account
  39.     {
  40.         private string name;
  41.         public string Name
  42.         {
  43.             get { return name; }
  44.             set { name = value; }
  45.         }
  46.         private decimal balance;
  47.         public decimal Balance
  48.         {
  49.             get { return balance; }
  50.             set { balance = value; }
  51.         }
  52.         public Account( string name , decimal balance )
  53.         {
  54.             this.name = name;
  55.             this.balance = balance;
  56.         }
  57.     }
  58. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值