获取枚举标志的所有位的最佳方法?
我有一个带有 Flags 属性的枚举。
我的问题是,我想获得所有选项的整数位掩码,而无需自己手动组合所有位。 我想这样做是为了与其他一些 int 字段进行比较,并且我想保护以防未来的开发人员向枚举添加更多位选项。
另一件事是我的枚举标志中的位将全部手动分配,所以我不能简单地获取下一个值并减去 1。
I have an enum with a Flags attribute.
My question is, I'd like to get an integer bitmask of all of the options without manually combining all the bits myself.
I want to do this to compare to some other int field, and I want to protect in case a future developer ads more bit options to the enum.
Another thing is the bits in my enum flags will be all manually assigned, so I cannot simply get the next value and subtract 1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果我正确理解了您的要求,这应该对您有用:
然后您可以将其转换回您的
typeof(Enum)
:If I understood what you asked correctly this should work for you:
You can then cast it back to your
typeof(Enum)
:看看我的 Unconstrained Melody 项目,它做了一些邪恶的事情来允许构建好的功能仅限于枚举和委托的通用方法。
在这种情况下,我认为您需要调用
Flags.GetUsedBits()
。如果您不介意使用额外的(非常小的)库,我想 Unconstrained Melody 会让处理标志时的生活变得更加美好。如果您有任何功能请求,我很乐意查看:)
Have a look at my Unconstrained Melody project, which does evil things to allow nice features to be built on generic methods constrained to enums and delegates.
In this case, I think you'd want to call
Flags.GetUsedBits<YourEnumType>()
.If you don't mind using an extra (very small) library, I'd like to think that Unconstrained Melody makes life nicer when dealing with flags. If you have any feature requests, I'd be happy to have a look :)
有点粗糙,但类似这样的东西?
Kind of crude but something like this?
这是一种方法,使用 Jon 编写的 通用运算符 中的想法Skeet 和 Marc Gravell:
此代码动态创建一个委托,将枚举值与 OR 运算符组合起来
Here's a way to do it, using ideas from the generic operators written by Jon Skeet and Marc Gravell :
This code dynamically creates a delegate that combines enum values with the OR operator