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);
        }
    }
}

posted on 2011-11-15 22:34  breakpoint  阅读(107)  评论(0编辑  收藏  举报

导航