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