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

后端 未结 7 1166
轻奢々
轻奢々 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:17

    I've come up against this before myself. It's by design in the .NET Framework:

    If the underlying value of flag is zero, the method returns true. If this behavior is not desirable, you can use the Equals method to test for equality with zero and call HasFlag only if the underlying value of flag is non-zero, as the following example illustrates.

    You can read a little more about this in the MSDN article here: http://msdn.microsoft.com/en-GB/library/system.enum.hasflag.aspx

    0 讨论(0)
  • 2020-12-11 00:30

    From MSDN

    The HasFlag method returns the result of the following Boolean expression.

    thisInstance And flag = flag
    
    0 讨论(0)
  • 2020-12-11 00:32

    This is just the defined behavior of the HasFlag method. From the MSDN documentation

    if the underlying value of flag is zero, the method returns true

    0 讨论(0)
  • 2020-12-11 00:34

    HasFlag is effectively this:

    HasFlag = (GivenFlag & Value) == GivenFlag;
    
    //"Anything" AND 0 == 0  --> always true
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 00:39

    I ended up removing the 'None' element. It is a 'magic value' and interferes with proper Flags Enum operations (like HasFlag()).

    If there is no value then use Nullable i.e. Animals? (which now supports primitive types)

    EDIT: I needed a 'Default' value (that is non-zero) for use in a serializable object in order to avoid using Nullable (which conflicted with the business logic). But I think this is still better than using 'None=0'.

    0 讨论(0)
提交回复
热议问题