检查是否所有 Enum 值均未设置
是否可以使用 ONE-Liner (其他正常方式...)来检查是否设置了所有可能的枚举状态?
从枚举水果中我想知道它是否未设置意味着没有香蕉,没有苹果,没有瓜。
我怎样才能做到这一点?
Is it possible with a ONE-Liner (else the normal way...) to check if any of all possible enum states are set?
From enum fruits I want to know wether it is unset means no banana, no apple, no melon.
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
就
myFlags == 0
足够了吗? 0 表示没有设置位,假设您正在使用标志并且没有对这些值执行任何奇怪的操作。
给定这个枚举:
并且这段代码:
它执行您期望的操作,但是它检查底层值而不执行按位操作,因此,如果您错误地改变底层值,您就会开始遇到问题,但您会得到其他问题问题也是如此。
鉴于:
并且:
也表现良好。
Would:
myFlags == 0
Suffice? 0 represents no bits set, assuming you are using flags and not doing anything funky with the values.
Given this enum:
And this code:
It does what you'd expect it to, however it is checking the underling value not doing bitwise ops, so if you mutate the underling value incorrectly you start to get issues, but you'll get other issues as well.
Given:
And:
Also behaves.
通过这种方式,您可以检查是否
value == Fruit.None
value == Fruit.All
(value & ~Fruit.All) != 0
请参阅 IDEOne
This way you could check whether
value == Fruit.None
value == Fruit.All
(value & ~Fruit.All) != 0
See this on IdeOne
假设您正在谈论设置为位标志的枚举,MSDN 有一个很好的例子:
要检查是否设置了位标志,您可以这样做:
理论上,您可以将所有按位操作放在一行上,并用
&
或|
取决于您的意图。Assuming you are talking about an enumeration that is setup as Bit Flags, MSDN has a good example:
to check whether a bit flag is set, you could, for example do this:
In theory, you could put all of your bitwise operations on one line separated by an
&
or|
depending on your intent.我建议枚举包含一个默认的“非设置”成员,例如值为
0
或0x0
的Fruit.None
。这样,任何具有枚举Fruit
类型的“非设置”成员都可以默认设置为Fruit.None
。和
I would recommend that the enum contain a default, "non set" member such as
Fruit.None
with the value of0
or0x0
. That way, any "non set" member with the type of enumFruit
could be set as default toFruit.None
.And