泛型方法

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace 泛型方法
  5. {
  6.     class Program
  7.     {
  8.         public interface IAccount
  9.         {
  10.             decimal Balance { get;}
  11.         }
  12.         public class Account : IAccount 
  13.         {
  14.             private string mName;
  15.             public string Name
  16.             {
  17.                 get
  18.                 {
  19.                     return mName;
  20.                 }
  21.                 set
  22.                 {
  23.                     mName = value;
  24.                 }
  25.             }
  26.             private decimal mBalance;
  27.             public decimal Balance
  28.             {
  29.                 get
  30.                 {
  31.                     return mBalance;
  32.                 }
  33.                 set
  34.                 {
  35.                     mBalance = value;
  36.                 }
  37.             }
  38.             public Account(string name, decimal balance)
  39.             {
  40.                 this.mName = name;
  41.                 this.mBalance = balance;
  42.             }
  43.         }
  44.         public static class Algorithm
  45.         {
  46.             public static decimal Accoumulate<TAccount>(IEnumerable<TAccount> coll) where TAccount : IAccount
  47.             {
  48.                 decimal sum = 0;
  49.                 foreach (TAccount account in coll)
  50.                 {
  51.                     sum += account.Balance;
  52.                 }
  53.                 return sum;
  54.             }
  55.         }
  56.         static void Main(string[] args)
  57.         {
  58.             List<Account> Accounts = new List<Account>();
  59.             Accounts.Add(new Account("",1500));
  60.             Accounts.Add(new Account("",1500));
  61.             Accounts.Add(new Account("",1500));
  62.             Accounts.Add(new Account("",1500));
  63.             Accounts.Add(new Account("",1500));
  64.             Console.WriteLine(Algorithm.Accoumulate<Account>(Accounts));
  65.             Console.ReadLine();
  66.         }
  67.     }
  68. }

    
 除了定义泛型类之外,还可以定义泛型方法,在泛型方法中,泛型类型用方法声明来定义。
 《C# 2005 & .Net3.0 高级编程第5版》
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值