为什么我的枚举比较找不到适当的价值?

发布于 2025-02-06 17:52:26 字数 414 浏览 0 评论 0 原文

我正在尝试从对象列表中找到特定的枚举。这是代码:

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%确定列表中有一件具有果酱功能的设备。

I am trying to find a specific Enum from a list of objects. Here is the code:

foreach (IEquipment eq in EntityEquipmentList)
{
if (eq.capability == capabilityEnum.Jam)
{
Console.WriteLine(eq.ToString())
}
}

Just to be clear, EntityEquipmentList is a List of IEquipment objects and I am trying to find the one that has "Jam" as it's capability. As you can see in the "if" statement, I want the capability of "Jam".

Enum in question:

Radar = 1
Jam = 2
Radio = 4
LowFreq = 8
HighFreq = 16

And to be clear, I am 100% certain that there is a piece of Equipment in the list with the Capability of Jam.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亚希 2025-02-13 17:52:26

请注意,您的功能枚举中的值是“两个的幂”(1、2、4、8,...,而不是1、2、3、4,...)。这通常是针对 flag枚举进行的,其中枚举值可以是不同定义值的组合。例如,设备可以具有 Jammer 的功能以及 Radar

好吧,现在 jammer + radar (或,确切: jammer | radar ,使用bitwise OR)不等于 jammer ,这是为什么您的比较失败。您可以通过使用 hasflag 而不是 equals

if (equipmentCapability.HasFlag(CapabilityEnum.Jammer)) { ... }

此外,还应添加 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 as Radar.

Well, now Jammer + Radar (or, to be precise: Jammer | Radar, using bitwise OR) is not equal to Jammer, which is why your comparison fails. You can fix this by using HasFlag instead of Equals:

if (equipmentCapability.HasFlag(CapabilityEnum.Jammer)) { ... }

In addition, you should add the Flags attribute to your enum. This

  • documents the fact that these enum values can be combined, and also
  • causes equipmentCapability.ToString() to output Jammer, Radar instead of the numerical value.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文