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

带委托并且带约束的泛型方法

时间:2015-08-26 23:51:45      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

    public interface ITest
    {
        decimal Balance { get; }
    }
public class Test : ITest
    {
        public Test(decimal balance)
        {
            this._balance = balance;
        }
        private decimal _balance;
        public decimal Balance
        {
            get
            {
                return _balance;
            }
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            List<Test> list = new List<Test>() { new Test(23), new Test(5) };
            decimal amount = Accumulate<Test, decimal>(list, (item, sum) => sum += item.Balance);
            Console.WriteLine(amount);
            Console.ReadKey();
        }

        public static T2 Accumulate<T1, T2>(List<T1> source, Func<T1, T2, T2> action) where T1 : ITest where T2 : struct
        {
            T2 sum = default(T2);
            foreach (T1 item in source)
            {
                sum = action(item, sum);
            }
            return sum;
        }
    }

 

带委托并且带约束的泛型方法

标签:

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

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