简体   繁体   English

C#检查Flags枚举是否只有一个值集

[英]C# Check if Flags enum has only one value set

I have a Flags enum and want to assert that a given instance of it, is one of the primitive values, ie it has exactly one '1' in its binary representation, ie it's a power of two. 我有一个Flags枚举,并希望断言它的给定实例是原始值之一,即它的二进制表示中只有一个'1',即它是2的幂。

What's the best way to check this? 检查这个的最佳方法是什么?

(I suppose "best" isn't necessarily well-defined, so ...) (我认为“最好”不一定定义明确,所以...)

  • What's the fastest way to check this? 检查这个的最快方法是什么?
  • What's the most semantically clear way to check this? 检查这个语义最明确的方法是什么?
  • How do I check this, whilst writing the least code? 在编写最少的代码时如何检查?

Using Framework functionality and be more flexible concerning the number of set flags one could use something like: 使用框架功能并且在设置标志数量方面更灵活,可以使用以下内容:

[Flags] 
public enum FlagsEnum {
   None = 0,
   One = 1,
   Two = 2,
   Three = 4,
}

void Main()
{
    var flags = FlagsEnum.Two;
    var hasOneElement = Enum.GetValues(typeof(FlagsEnum)).OfType<FlagsEnum>().Where(i => i != FlagsEnum.None && flags.HasFlag(i)).Count() == 1;
}

bit operation will yield the fastest result 位操作将产生最快的结果

((anInstanceOfTheFlaggedEnum & (anInstanceOfTheFlaggedEnum -1)) != 0)

over the more readable built in function 通过更具可读性的内置函数

Enum.IsDefined(typeof(yourFlaggedEnumType), anInstanceOfTheFlaggedEnum)

I just ran a test and it was ~175 times faster.. 我刚刚进行了测试,速度提高了约175倍..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM