![](/img/trans.png)
[英]Can I use an ENUM instead of a switch statement with Enums in the CASE?
[英]How to use enum array parameter on switch case statement?
我有以下方法:
private int EarthAttributeValue()
{
var totalValue = 0;
foreach (var item in ItemList)
{
switch (item.Attribute)
{
case AttributeEnum.Earth:
totalValue += item.AttributeValue;
break;
}
}
return totalValue;
}
但我不想为我的枚举中的每个值创建一个新方法,所以我试图为任何属性创建一个通用方法,接收“目标枚举”作为参数。
我试过这个
private int AttributeValue(AttributeEnum attribute)
{
var totalValue = 0;
foreach (var item in ItemList)
{
switch (item.Attribute)
{
case attribute:
totalValue += item.AttributeValue;
break;
}
}
return totalValue;
}
但它没有建立,说我需要一个常数值(因为参数是一个变量)。
有什么办法吗? 也许使用反射?
Obs.:我不想使用 if 而不是 switch,因为 item.Attribute 很快就会成为一个列表,因此作为参数。
我创建了这个,将开关替换为 Linq lambda :
internal int AttributeValue(AttributeEnum attribute)
{
return ItemList
.Where(x => x.Attribute == attribute)
.Sum(x => x.AttributeValue);
}
感谢@TimSchmelter 的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.