如何在switch case中使用枚举参数实现通用属性值统计方法?
解决方案
你遇到的问题是因为C#中switch的case分支必须是编译时常量,而方法参数attribute是运行时变量,所以无法通过编译。不需要用反射,有更简洁高效的实现方式,还能适配后续属性变为列表的需求:
1. 针对当前单属性的场景(用LINQ简化)
直接用LINQ的Where过滤出匹配属性的项,再用Sum累加值,代码比循环+switch简洁得多:
private int AttributeValue(AttributeEnum targetAttribute) { return ItemList.Where(item => item.Attribute == targetAttribute) .Sum(item => item.AttributeValue); }
2. 适配后续属性变为列表的场景
如果后续item.Attribute变成属性列表(比如List<AttributeEnum>),参数也变为目标属性列表,只需调整判断逻辑,比如判断item的属性列表和目标列表是否有交集:
// 统计item属性列表与目标列表存在交集的项的总值 private int AttributeValue(List<AttributeEnum> targetAttributes) { return ItemList.Where(item => item.Attributes.Intersect(targetAttributes).Any()) .Sum(item => item.AttributeValue); } // 另一种写法:统计item属性列表包含目标列表中任意属性的项的总值 private int AttributeValue(List<AttributeEnum> targetAttributes) { return ItemList.Where(item => targetAttributes.Any(attr => item.Attributes.Contains(attr))) .Sum(item => item.AttributeValue); }
这种方式完全不需要switch或if的繁琐分支,代码可读性和扩展性都更强,完美匹配你后续的需求变化。
内容的提问来源于stack exchange,提问作者mr90
相关产品推荐
相关产品推荐

