简体   繁体   中英

What's the best expression to determine whether a specific flag is set

I'm using this code to determine whether a specific flag is set. Is there any short expression (without repeating someFlag.flag1 twice)?

[Flag]
enum someFlag
{
    flag1 = 0x0,
    flag2 = 0x2,
    flag3 = 0x4
}

if ((someFlag & someFlag.flag1) == someFlag.flag1)

If there isn't then, I would create an extension method. Any idea?

If you're using .NET4 then you can use the built-in HasFlag method.

if (yourValue.HasFlag(someFlag.flag1)) DoSomething();

In earlier versions of the framework then what you've already got is fine (I think that's exactly what HasFlag does behind the scenes).

Using Unconstrained Melody , you can get the benefits of Enum.HasFlag without requiring .NET 4, with added type safety, and without boxing:)

if (foo.HasAll(SomeFlag.Flag1))

(There are HasAny and HasAll methods, as the argument you pass can contain multiple flags to match.)

Try:

if ((someFlag & someFlag.flag1) != 0)

Also, you shouldn't have flag1 = 0 - it needs to be 0x01, otherwise flags won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM