检查枚举是否设置了标志的 C# 扩展方法

发布于 2024-09-27 12:27:45 字数 382 浏览 1 评论 0原文

我想创建一个扩展方法来检查枚举是否有标志。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寒尘 2024-10-04 12:27:45

.NET 4 已经包含此功能,因此,如果可能的话,请升级。

days.HasFlag(DaysOfWeek.Monday);

如果无法升级,这里是该方法的实现:

public bool HasFlag(Enum flag)
{
    if (!this.GetType().IsEquivalentTo(flag.GetType())) {
        throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); 
    }

    ulong uFlag = ToUInt64(flag.GetValue()); 
    ulong uThis = ToUInt64(GetValue());
    return ((uThis & uFlag) == uFlag); 
}

您可以轻松构建等效的扩展方法:

public static bool HasFlag(this Enum @this, Enum flag)
{
    // as above, but with '@this' substituted for 'this'
}

.NET 4 already includes this funcitonality so, if possible, upgrade.

days.HasFlag(DaysOfWeek.Monday);

If it's not possible to upgrade, here is the implementation of said method:

public bool HasFlag(Enum flag)
{
    if (!this.GetType().IsEquivalentTo(flag.GetType())) {
        throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); 
    }

    ulong uFlag = ToUInt64(flag.GetValue()); 
    ulong uThis = ToUInt64(GetValue());
    return ((uThis & uFlag) == uFlag); 
}

You could easily build the equivalent extension method:

public static bool HasFlag(this Enum @this, Enum flag)
{
    // as above, but with '@this' substituted for 'this'
}
执笔绘流年 2024-10-04 12:27:45

我最近遇到了这个问题。

如果您不知道 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文