TestGenericClass

using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
    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.name = name;
            this.balance = balance;
        }
    }

    public class Algorithm
    {
        public static decimal Total<ee>(IEnumerable<ee> e) where ee : IAccount //声明泛型方法, 使用where子句限制泛型类型   
        {
            decimal total = 0;
            foreach (ee a in e)
            {
                total += a.Balance;
            }
            return total;
        }
    }

    public class TestMethodTTwo
    {
        public static void Main55()
        {
            List<Account> accounts = new List<Account>();
            accounts.Add(new Account("Magic", 9999.99m));
            accounts.Add(new Account("Haha", 1241.33m));
            accounts.Add(new Account("Heihei", 1551.2m));
            accounts.Add(new Account("Kevin", 2643m));

            //调用泛型方法     
            decimal total = Algorithm.Total(accounts);
            Console.WriteLine("Total : {0:C}", total);
        }
    }
}

转载于:https://www.cnblogs.com/calvin88/archive/2011/11/15/2250399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值