测试单个值的[Flags]枚举值 [英] Testing a [Flags] enum value for a single value

查看:132
本文介绍了测试单个值的[Flags]枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个标有 [Flags] 枚举,.NET中是否有一种方法来测试这个类型的值是否只包含一个值?我可以使用比特计算得到我想要的结果,但是如果可能,我宁愿使用内置函数。

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.

当循环执行枚举动态值, Enum.GetValues()也返回组合标志。在以下示例中调用枚举上的该函数返回4个值。但是,我不希望包含在内部算法中的组合。测试个人枚举值为平等是因为枚举可能包含许多值,并且还需要额外的维护当枚举值更改时。

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)
{
    // ???
}




相关: StackOverflow:枚举在组合标志上的定义

推荐答案

您可以将其转换为 int ,并使用 Bit Twiddling Hacks 来检查是否有两个权力。

You can cast it to int and use the techniques from Bit Twiddling Hacks to check if it's a power of two.

int v = (int)enumValue;
return v != 0 && (v & (v - 1)) == 0;

这篇关于测试单个值的[Flags]枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆