C#:检查一组枚举值的最佳方法?
假设你有 enum MyEnum {A = 0, B = 1, C = 2, D = 4, E = 8, F = 16};
在某些时候,您有一个函数可以检查 MyEnum 的实例并如果是 C、D 或 F,则返回 true
bool IsCDF(MyEnum enumValue)
{
return //something slick
}
我记得有一些非常巧妙的方法来进行位移并执行此操作,该方法比一堆三元 if 语句读起来更好,但对于我的生活,我不记得了什么 这是。
有人知道吗?
suppose you haveenum MyEnum {A = 0, B = 1, C = 2, D = 4, E = 8, F = 16};
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
}
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.
Anyone know?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果将其设为
[Flags]
枚举,则可以为每个枚举值分配不同的位值(1、2、4、8、16...)。然后,您可以使用按位运算来确定某个值是否是一组可能值中的一个。因此,要查看它是 C、D 还是 F:
或使用
HasFlag()
(效率较低,但可读性更强):请注意,这对于 0 值不起作用(在您的示例中, 'A'),并且您必须小心所有枚举值都解析为唯一的位值(即 2 的非零幂)。
这种方法的优点是:
方便提示:
定义 [Flags] 枚举时,使用左移 (
<<
) 使位值更清晰(并且更难出错),尤其是对于高阶位: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.So, to see if it is C, D, or F:
or using
HasFlag()
(less efficient but more readable):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).
The advantages of this approach are:
Handy hint:
When defining [Flags] enums, use left-shift (
<<
) to make the bit values clearer (and much harder to get wrong) especially for higher-order bits:我可能会使用 Unconstrained Melody 作为保持事情整洁的方式:
我可能会提取命名常量中的“C、D 或 E”位 - 可能在枚举本身中,如果它有意义的话:
I'd possibly use Unconstrained Melody as a way of keeping things tidy:
I'd probably extract the "C, D or E" bit into a named constant - possibly in the enum itself, if it had meaning:
这是我创建的一个扩展,它允许您查看给定的枚举值是否位于枚举值的可能选择的变量列表中。
用法
Here is an extension I created that allows you to see if your given Enum value is in a variable list of possible choices of Enum values.
Usage
您可能正在考虑 FlagsAttribute。请查看此处和此处查看一些示例。
您可以使用 Enum.HasFlag 方法
May be you are thinking of FlagsAttribute. Look at here and here for some examples.
You could use Enum.HasFlag Method
也许这个扩展类对你有用:
Maybe this extension class is usefull for you:
在 c# 8 中你可以这样做:
使用扩展方法方式:
否则你可以这样做:
in c# 8 you can do:
Using an extension method way:
otherwise you could do: