深入理解 c# 第十四章 深入理解 c# 第十四章 对TimeSpan列表中的元素进行动态求和 弥补泛型操作符的不足

	static class DynamicSumExtensions
    {
        public static T DynamicSum<T>(this IEnumerable<T> source)
        {
            dynamic total = default(T);
			//total {00:00:00}
            foreach (T element in source)
			//element {00:00:00}  {02:00:00} {00:25:00} {00:00:30} {00:00:45}
			//{00:40:00}
            { 
                total = (T) (total + element);
				//total {02:00:00}  {02:25:00} {02:25:30} {02:26:15} {03:06:15}
            }
            return total;
        }
    }
    static class TimeSpanExtensions
    {
        internal static TimeSpan Hours(this int hours)
		//hours 2
        {
            return TimeSpan.FromHours(hours);
        }

        internal static TimeSpan Minutes(this int minutes)
		//minutes 25 40
        {
            return TimeSpan.FromMinutes(minutes);
        }

        internal static TimeSpan Seconds(this int seconds)
		//seconds 30 45 
        {
            return TimeSpan.FromSeconds(seconds);
        }
    }

    class DynamicTimeSpanSum
    {
        static void Main()//对TimeSpan列表中的元素进行动态求和  弥补泛型操作符的不足
        {
            var times = new List<TimeSpan>
            {                 
                2.Hours(), 25.Minutes(), 30.Seconds(),
                45.Seconds(), 40.Minutes()
            };
            Console.WriteLine(times.DynamicSum());
        }
    }




  TimeSpan的值使用扩展方法创建,求和过程是动态了,总跨度是3小时6分钟15秒。
  相加的结果强制转换回T,虽然接下来又将其赋值给了动态类型。
  
输出
03:06:15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值