开发者

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜