HasFlag always returns True

前端 未结 5 685
有刺的猬
有刺的猬 2021-01-06 07:39

There is a way to check if I got a flag in a series of flag?

Example:

[Flags]
Enum TestEnum
{
  ALIVE, DEAD, ALMOSTDEAD, HURT, OTHERS

}
// check if          


        
5条回答
  •  情深已故
    2021-01-06 08:28

    You can certainly use Enum.HasFlag like everyone has suggested. However, its important to make sure that your enumeration falls in powers of two. Powers of two have a single bit set, so your enumeration should look like this:

    Enum TestEnum
    {
        ALIVE = 1, DEAD = 2, ALMOSTDEAD = 4, HURT = 8, OTHERS = 16
    }
    

    The reason this is important is because you are comparing the bit flags. In memory, your enum flags will look like this:

    ALIVE      = 00001
    DEAD       = 00010
    ALMOSTDEAD = 00100
    HURT       = 01000
    OTHERS     = 10000
    

    When you do a bitwise compare, like DEAD | ALMOSTDEAD, you are doing this:

    DEAD       = 00010
               OR
    ALMOSTDEAD = 00100
    ------------------
    RESULT     = 00110
    

    Since the Result is > then 0, its true.

提交回复
热议问题