首页 > 其他 > 详细

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

时间:2015-08-26 23:50:02      阅读:278      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!