C#:最好的方式来检查一组枚举值? [英] C#: Best way to check against a set of Enum Values?

查看:109
本文介绍了C#:最好的方式来检查一组枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有
枚举MyEnum {A = 0,B = 1,C = 2,D = 4,E = 8,F = 16};

在某些时候,你有一个函数将检查MyEnum的一个实例,如果它是C,D或F,返回true

At some point you have a function that will check an instance of MyEnum and return true if it is C,D, or F

bool IsCDF(MyEnum enumValue) 
{
  return //something slick
}

我记得有一些非常光滑的方法来做点位移动,并将这个操作放在比一堆三元if语句更好的方式,但是我的生活不记得了。

I remember that there was some really slick way to do bit shifting and preform this operation that read way better than a bunch of ternary if statements but for the life of me I can't remember what it is.

任何人都知道?

推荐答案

如果将其设置为[Flags]枚举,则可以为每个枚举值分配不同的位值(1,2,4,8,16 ...)。然后,您可以使用按位操作来确定值是否是一组可能的值。

If you make it a [Flags] enum, you can assign a different bit value (1, 2, 4, 8, 16...) to each enumerated value. Then you can use a bitwise operation to determine if a value is one of a set of possible values.

因此,要查看是C,D还是F:

So, to see if it is C, D, or F:

bool IsCDF(MyEnum enumValue)
{
    return((enumValue & (MyEnum.C | MyEnum.D | MyEnum.F)) != 0);
}

请注意,这个值不适用于0(在您的示例中, 'A'),并且您必须小心所有枚举值都解析为唯一的位值(即非零幂的两个值)。

Note that this will not work for a value of 0 (in your example, 'A'), and you must be careful that all enum values resolve to unique bit values (i.e. non-zero powers of two).

这种方法的优点是:


  • 通常需要执行一个CPU指令,而进行三个单独的if检查将需要3个或更多的指令在您的目标平台上)。

  • 您可以将要测试的值集合作为枚举值(单个整数)传递,而不需要使用枚举值列表。 / li>
  • 您可以使用按位操作进行许多其他有用的操作,通常使用数字/比较方法,这些操作会变得笨拙和缓慢。

这篇关于C#:最好的方式来检查一组枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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