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

后端 未结 7 1203
轻奢々
轻奢々 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

提交回复
热议问题