我如何确定一个Enum值是否具有一个或多个与之比较的值? [英] How do I determine if an Enum value has one or more of the values it's being compared with?
问题描述
我有一个标有[Flags]属性的枚举,如下所示:
I've got an Enum marked with the [Flags] attribute as follows:
[Flags]
public enum Tag : int
{
None = 0,
PrimaryNav = 1,
HideChildPages = 2,
HomePage = 4,
FooterLink = 8
}
在站点地图的sitemapnodes上,我将标记组合的int值存储为属性。
On sitemapnodes in my sitemap I store the int value for the tags combination as an attribute.
我需要做的是检查节点是否具有 任何一个 的一个或多个标签,例如Tag.PrimaryNav | Tag.HomePage。
What I need to do is check if a node has any one of one or more tags, e.g. Tag.PrimaryNav | Tag.HomePage.
我正在努力使用必要的布尔逻辑来确定Enum值是否具有要比较的一个或多个值。
I'm struggling with the necessary boolean logic to determine if an Enum value has one or more of the values it's being compared with.
不好意思,不好意思。如有必要,我可以提供更多信息。
Apologies if this isn't clear. I can provide more information if necessary.
推荐答案
您可以通过将值与 |组合在一起来做到这一点code>并通过
&
进行检查。
You can do that by combining values with |
and checking via &
.
检查值是否包含或标签:
if ((myValue & (Tag.PrimaryNav | Tag.HomePage)) != 0) { ... }
|
通过按位屏蔽将要测试的枚举(按位)和&
测试结合在一起-如果结果不为零,则至少设置其中一个。
The |
combines the enums you're testing (bitwise) and the &
tests via bitwise masking -- if the result isn't zero, it has at least one of them set.
如果要测试是否同时设置了它们和,也可以这样做:
If you want to test whether it has both of them set, you can do that as well:
Tag desiredValue = Tag.PrimaryNav | Tag.HomePage;
if ((myValue & desiredValue) == desiredValue) { ... }
在这里,我们掩盖了所有无关的内容,并测试了结果值是否等于我们要做的所关心的(我们不能使用!= 0
像以前一样,因为它将与 值匹配,在这里我们对 both 都感兴趣)。
Here we're masking off anything we don't care about, and testing that the resulting value equals what we do care about (we can't use != 0
like before because that would match either value and here we're interested in both).
某些链接:
- The
&
Operator - The
|
Operator
这篇关于我如何确定一个Enum值是否具有一个或多个与之比较的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!