如何设置枚举标志的所有位
我想知道将 enum
标志的所有位设置为 1 的通用方法。 我只是想要一个 enum
,它会返回所有比较,而不管其他枚举如何。
这段代码有效;
[Flags]
public enum SomeRightEnum : uint
{
CanDoNothing = 0,
CanDoSomething = 1 << 0,
CanDoSomethingElse = 1 << 1,
CanDoYetAnotherThing = 1 << 2,
...
DoEverything = 0xFFFFFFFF
}
但在上面的代码中,由于它是 uint,所以我们设置了“F”的数量,如果它是 int,则不起作用。
因此,我将欣赏一种将 enum
标志的所有位设置为 1 的通用方法,无论数据类型如何(i
nt、int64
、<代码>uint等)
I wonder a generic way for setting all bits of enum
flag to 1.
I just would like to have an enum
which returns for all comparisons, regardless of other enums.
And this code works;
[Flags]
public enum SomeRightEnum : uint
{
CanDoNothing = 0,
CanDoSomething = 1 << 0,
CanDoSomethingElse = 1 << 1,
CanDoYetAnotherThing = 1 << 2,
...
DoEverything = 0xFFFFFFFF
}
But at the code above since it is uint we set the number of "F"s, it wouldn't work if it was int
.
So I'll appreciate a generic way of setting all bits of enum
flag to 1, regardless of the datatype (i
nt, int64
, uint
etc)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单的可能是:
对于基于无符号的枚举:
Easiest is probably:
For unsigned based enum:
这是你想要的吗?
Was this what you wanted?
如果有人想知道:
我需要为 WPF 构建一个可绑定枚举转换器进行相同的操作。
由于我不知道反射中这些值的含义,因此我需要手动切换值(将它们绑定到复选框 pe)
将 Flagged 枚举的值设置为 -1 来设置所有位时出现问题。
如果将其设置为 -1 并取消标记所有值,则不会导致 0,因为所有未使用的位都不会取消标记。
这最适合我的情况。
或者,如果您想要扩展方法:
In case someone is wondering:
I needed to do the same building a Bindable enumconverter for WPF.
Since I don't know what the values mean in Reflection, I needed to manually been able to switch values (binding them to a checkbox p.e.)
There is a problem setting the value of a Flagged enum to -1 to set all the bits.
If you set it to -1 and you unflag all values it will not result in 0 because all unused bits are not unflagged.
This is wat worked best for my situation.
Or if you would want an extension method:
我发现
All = ~0
更优雅,但从 C# 7.0 开始,为了获得更高的透明度,您可以将0b0101010111
等二进制文字与数字分隔符一起 使用_
如0b_0101_0101_11
。因此,要为
Int32
设置所有标志,您可以选择以下可能性之一,它们都是相同的:I find
All = ~0
more elegant, but to have more transparency starting from C# 7.0 you can usebinary literals like
0b0101010111
together with digit separators_
like0b_0101_0101_11
.So to set all flags for the
Int32
you can chose one of the following possibilities, all of them are the same: