检查枚举是否设置了标志的 C# 扩展方法
我想创建一个扩展方法来检查枚举是否有标志。
DaysOfWeek workDays = DaysOfWeek.Monday | DaysOfWeek.Tuesday | DaysOfWeek.Wednesday;
// instead of this:
if ((workDays & DaysOfWeek.Monday) == DaysOfWeek.Monday)
...
// I want this:
if (workDays.ContainsFlag(DaysOfWeek.Monday))
...
我怎样才能做到这一点? (如果有一个类已经做到了这一点,那么我将不胜感激如何对其进行编码的解释;我已经用这个方法搞得太久了!)
提前致谢
I want to make an extension method to check if an enumeration has a flag.
DaysOfWeek workDays = DaysOfWeek.Monday | DaysOfWeek.Tuesday | DaysOfWeek.Wednesday;
// instead of this:
if ((workDays & DaysOfWeek.Monday) == DaysOfWeek.Monday)
...
// I want this:
if (workDays.ContainsFlag(DaysOfWeek.Monday))
...
How can I accomplish this? (If there is a class that already does this then I would appreciate an explanation to how this can be coded; I've been messing around with this method far too long!)
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.NET 4 已经包含此功能,因此,如果可能的话,请升级。
如果无法升级,这里是该方法的实现:
您可以轻松构建等效的扩展方法:
.NET 4 already includes this funcitonality so, if possible, upgrade.
If it's not possible to upgrade, here is the implementation of said method:
You could easily build the equivalent extension method:
我最近遇到了这个问题。
如果您不知道 Enum 的类型是什么,那么您可以将 Enum 转换为 int 并使用 Enum 静态方法将 Enum 字段名称解析为值并使用 op_BitwiseAnd 比较这些值。
如果您有兴趣,我稍后会用代码更新此内容,但我现在要出门了。
I recently ran into this problem.
If you don't know what the type of the Enum is, then you can cast he Enum to an int and use the Enum static methods to parse an Enum field name into a value and use op_BitwiseAnd to compare the values.
I'll update this later with the code if you're interested, but am heading out the door now.