Swift:如何实现接收数组及元素属性的特定时间统计函数?
解决结构化数组灵活提取时间属性统计总时长的问题
核心方案:使用委托封装属性访问逻辑
最安全且高效的方式是通过Func<T, TimeSpan>委托将“从数组元素中提取目标时间属性”的逻辑作为参数传入,避免直接传属性名字符串带来的编译时检查缺失和反射性能问题。
假设你的Flight类定义如下:
public class Flight { public TimeSpan SeTime { get; set; } public TimeSpan DepartureTime { get; set; } // 其他业务属性 }
修改后的FlightLibrary类及通用函数实现:
public class FlightLibrary { // 通用统计函数:接收Flight数组和属性选择委托 public TimeSpan GetSpecificTotalTime(Flight[] flights, Func<Flight, TimeSpan> timePropertySelector) { TimeSpan totalDuration = TimeSpan.Zero; foreach (var flight in flights) { totalDuration += timePropertySelector(flight); } // 用LINQ可以简化为一行: // return TimeSpan.FromTicks(flights.Sum(f => timePropertySelector(f).Ticks)); return totalDuration; } }
调用示例
需要统计哪个时间属性,直接通过Lambda表达式指定即可:
// 初始化测试数组 Flight[] testFlights = new[] { new Flight { SeTime = TimeSpan.FromHours(2.5) }, new Flight { SeTime = TimeSpan.FromHours(1.75) } }; var flightLib = new FlightLibrary(); // 统计SeTime总时长 TimeSpan totalSeTime = flightLib.GetSpecificTotalTime(testFlights, f => f.SeTime); // 后续要统计DepartureTime,只需修改Lambda TimeSpan totalDepartureTime = flightLib.GetSpecificTotalTime(testFlights, f => f.DepartureTime);
备选方案:使用反射(不推荐)
如果必须通过属性名字符串指定(比如从配置动态读取),可以用反射实现,但要注意编译时无法验证属性合法性,且性能不如委托:
public TimeSpan GetSpecificTotalTime(Flight[] flights, string propertyName) { TimeSpan totalDuration = TimeSpan.Zero; var propertyInfo = typeof(Flight).GetProperty(propertyName); if (propertyInfo == null || propertyInfo.PropertyType != typeof(TimeSpan)) { throw new ArgumentException($"属性 {propertyName} 不是有效的TimeSpan类型属性"); } foreach (var flight in flights) { var timeValue = (TimeSpan)propertyInfo.GetValue(flight); totalDuration += timeValue; } return totalDuration; }
调用时传入属性名字符串:
TimeSpan totalSeTime = flightLib.GetSpecificTotalTime(testFlights, "SeTime");
内容的提问来源于stack exchange,提问作者flyer74
相关产品推荐
相关产品推荐

