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

后端 未结 7 1199
轻奢々
轻奢々 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: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'.

提交回复
热议问题