- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace 泛型
- {
- class 泛型方法
- {
- public static void Main()
- {
- //将所有账目加入到List集合中
- List<Account> list = new List<Account>();
- list.Add( new Account( "aladdin" , 1000 ) );
- list.Add(new Account("zhaohaifu", 2000));
- list.Add(new Account("jacky", 3000));
- //计算总合
- decimal total = Algorithm.AccumulateSimple( list );
- Console.WriteLine( "账单总计:" + total );
- Console.ReadLine();
- }
- }
- //计算类
- class Algorithm
- {
- public static decimal AccumulateSimple<TAccount>( IEnumerable<TAccount> e )
- where TAccount : Account
- {
- decimal redec = 0 ;
- foreach( TAccount a in e )
- {
- redec += a.Balance;
- }
- return redec;
- }
- }
- //帐目类
- class Account
- {
- private string name;
- public string Name
- {
- get { return name; }
- set { name = value; }
- }
- private decimal balance;
- public decimal Balance
- {
- get { return balance; }
- set { balance = value; }
- }
- public Account( string name , decimal balance )
- {
- this.name = name;
- this.balance = balance;
- }
- }
- }
C#中泛型方法作用举例
最新推荐文章于 2025-03-15 16:17:13 发布