测试单个值的 [Flags] 枚举值
如果我有一个标有 [Flags]
的 enum
,.NET 中有没有办法测试这种类型的值以查看它是否只包含单个值?我可以使用位计数得到我想要的结果,但如果可能的话我宁愿使用内置函数。
动态循环枚举 enum
值时,Enum.GetValues()
也会返回组合标志。在以下示例中对 enum
调用该函数会返回 4 个值。但是,我不希望内部算法中包含值组合。测试各个 enum
值是否相等已经过时了,因为 enum
可能包含许多值,并且当 enum
中的值存在时,还需要额外的维护> 改变。
[Flags]
enum MyEnum
{
One = 1,
Two = 2,
Four = 4,
Seven = One | Two | Four,
}
void MyFunction()
{
foreach (MyEnum enumValue in Enum.GetValues(typeof(MyEnum)))
{
if (!_HasSingleValue(enumValue)) continue;
// Guaranteed that enumValue is either One, Two, or Four
}
}
private bool _HasSingleValue(MyEnum value)
{
// ???
}
If I have an enum
that's marked with [Flags]
, is there a way in .NET to test a value of this type to see if it only contains a single value? I can get the result I want using bit-counting, but I'd rather use built-in functions if possible.
When looping through the enum
values dynamically, Enum.GetValues()
returns the combination flags as well. Calling that function on the enum
in the following example returns 4 values. However, I don't want the value combinations included in the inner algorithm. Testing individual enum
values for equality is out, since the enum
could potentially contain many values, and it also requires extra maintenance when the values in the enum
change.
[Flags]
enum MyEnum
{
One = 1,
Two = 2,
Four = 4,
Seven = One | Two | Four,
}
void MyFunction()
{
foreach (MyEnum enumValue in Enum.GetValues(typeof(MyEnum)))
{
if (!_HasSingleValue(enumValue)) continue;
// Guaranteed that enumValue is either One, Two, or Four
}
}
private bool _HasSingleValue(MyEnum value)
{
// ???
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将其转换为
int
并使用 中的技术Bit Twiddling Hacks 检查它是否是 2 的幂。You can cast it to
int
and use the techniques from Bit Twiddling Hacks to check if it's a power of two.您可以结合使用
IsDefined
和检查 2 的幂。You can use a combination of
IsDefined
and checking for powers of 2.您可以使用 Enum.GetValues 并仅计算那些 2 的幂(可被 2 整除,没有余数)的项目。
You could you Enum.GetValues and count only those items that are a power of 2 (evenly divisible by 2 with no remainder).