开发者

C# extension method to check if an enumeration has a flag set

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


.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'
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜