HasFlags always returns true for None (0) value in enum

后端 未结 7 1186
轻奢々
轻奢々 2020-12-10 23:51

This is the enum definition:

[Flags]
enum Animals
{
    None = 0,
    Dog = 1,
    Cat = 2,
    Horse = 4,
    Zebra = 8,
}

Now, given the

7条回答
  •  失恋的感觉
    2020-12-11 00:34

    There is already a plethora of answers describing WHY this happens, so I will just add that what you can do to get what you're looking for is to not use HasFlag in that case, but instead do var hasNone = myAnimals == Animals.None.

    I personally really loathe extension methods, but it would be possible to put this in an extension on Enum if you really value being able to just write myOptionEnum.HasNoFlags(). I would just run with explicitly checking for the None value in this special case though.

提交回复
热议问题