为什么我的枚举比较找不到适当的价值?
我正在尝试从对象列表中找到特定的枚举。这是代码:
foreach (IEquipment eq in EntityEquipmentList)
{
if (eq.capability == capabilityEnum.Jam)
{
Console.WriteLine(eq.ToString())
}
}
要清楚,EntityEquipmentList是IEquipment对象的列表,我正在尝试找到具有“果酱”作为功能的列表。正如您在“ IF”语句中看到的那样,我想要“ jam”的功能。
有问题的枚举:
Radar = 1
Jam = 2
Radio = 4
LowFreq = 8
HighFreq = 16
要清楚,我100%确定列表中有一件具有果酱功能的设备。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,您的功能枚举中的值是“两个的幂”(1、2、4、8,...,而不是1、2、3、4,...)。这通常是针对 flag枚举进行的,其中枚举值可以是不同定义值的组合。例如,设备可以具有
Jammer
的功能以及Radar
。好吧,现在
jammer + radar
(或,确切:jammer | radar
,使用bitwise OR)不等于jammer
,这是为什么您的比较失败。您可以通过使用hasflag
而不是equals
:此外,还应添加
flags
属性到您的枚举。这equience capability.tostring()
输出jammer,radar
而不是数值值。Note that the values in your capabilities enum are "powers of two" (1, 2, 4, 8, ... instead of 1, 2, 3, 4, ...). This is usually done for flag enums, where an enum value can be a combination of different defined values. For example, an equipment could have the capability of
Jammer
as well asRadar
.Well, now
Jammer + Radar
(or, to be precise:Jammer | Radar
, using bitwise OR) is not equal toJammer
, which is why your comparison fails. You can fix this by usingHasFlag
instead ofEquals
:In addition, you should add the
Flags
attribute to your enum. ThisequipmentCapability.ToString()
to outputJammer, Radar
instead of the numerical value.