C#中如何引用对象变量作为参数?多列表求和优化方案
解决方法
要避免重复编写多个foreach循环,你可以通过合并列表或遍历列表集合的方式减少冗余代码,以下是几种实用方案:
方案1:用LINQ合并列表后求和(最简洁)
如果项目引用了System.Linq,可以直接把多个列表拼接成一个统一序列,再用Sum方法计算指定属性的总和:
// 替换Food为你实际的列表元素类型 public int GetCalories(Func<Food, int> propertySelector) { // 合并所有列表后,对指定属性求和 return list.Concat(list2).Concat(list3).Sum(propertySelector); }
调用时直接传入要累加的属性即可:
int total = GetCalories(food => food.Calories);
方案2:遍历列表集合手动累加(无需LINQ)
如果不想依赖LINQ,可以把所有列表放到一个数组中,只写一次内层foreach循环:
public int GetCalories(Func<Food, int> propertySelector) { int total = 0; // 遍历所有列表的集合 foreach (var itemList in new[] { list, list2, list3 }) { foreach (var item in itemList) { total += propertySelector(item); } } return total; }
补充:根据属性名字符串动态求和
如果你的name参数是用来指定要累加的属性名(比如传入"Calories"),可以用反射实现动态取值:
public int GetCalories(string propertyName) { var propertyInfo = typeof(Food).GetProperty(propertyName); if (propertyInfo == null || propertyInfo.PropertyType != typeof(int)) { throw new ArgumentException($"不存在名为{propertyName}的int类型属性"); } int total = 0; foreach (var itemList in new[] { list, list2, list3 }) { foreach (var item in itemList) { total += (int)propertyInfo.GetValue(item); } } return total; }
注意点
你示例中的ref int argument参数设计不合理——这里应该是指定对象的某个属性,而非传入int变量的引用。上面的方案用Func<YourType, int>委托可以更安全、直观地指定要累加的属性。
内容的提问来源于stack exchange,提问作者avihus
相关产品推荐
相关产品推荐

