码迷,mamicode.com
首页 > 其他好文 > 详细

带约束都泛型方法

时间:2015-08-26 22:05:40      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

public interface IAccount
    {
        decimal Balance { get; set; }
        string Name { get; }
    }
public class Account : IAccount
    {
        private decimal balance;
        public decimal Balance
        {
            get
            {
                return balance;
            }

            set
            {
                balance = value;
            }
        }

        public string Name
        {
            get
            {
                throw new NotImplementedException();
            }
        }
    }
private decimal _balance;
        public decimal Balance
        {
            get
            {
                return _balance;
            }

            set
            {
                _balance = value;
            }
        }

        public string Name
        {
            get
            {
                throw new NotImplementedException();
            }
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            List<Account> list = new List<Account>() { new Account() { Balance = 5 }, new Account() { Balance = 5 } };

            decimal retvalue = Accumulate<Account>(list);
            Console.WriteLine(retvalue);

            List<Bccount> list1 = new List<Bccount>() { new Bccount() { Balance = 8 }, new Bccount() { Balance = 6 } };
            decimal retvalue1 = Accumulate<Bccount>(list1);
            Console.WriteLine(retvalue1);

            Console.ReadKey();
        }

        public static decimal Accumulate<T>(List<T> source) where T : IAccount
        {
            decimal sum = 0;
            foreach (T a in source)
            {
                sum += a.Balance;
            }
            return sum;
        }
    }

 

带约束都泛型方法

标签:

原文地址:http://www.cnblogs.com/webczw/p/4761743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!