如果我有一个枚举
的标有1 [国旗]
,有没有办法在.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)
{
// ???
}
相关阅读:计算器:Enum.IsDefined上结合标志
Related: StackOverflow: Enum.IsDefined on combined flags
推荐答案
您可以将它转换成int和使用的技术来自的链接文本,以检查它是否为二的幂。
You can cast it to int and use the techniques from link text to check if it's a power of two.
相关推荐
最新文章