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

和自甴很熟 提交于 2019-11-30 21:36:16

问题


This is the enum definition:

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

Now, given the following code, why does the HasFlag method return true for the value Animals.None?

Animals myAnimals = Animals.Dog | Animals.Horse;

var hasNone = myAnimals.HasFlag(Animals.None);    //true! Why?
var hasCat = myAnimals.HasFlag(Animals.Cat);      //false
var hasDog = myAnimals.HasFlag(Animals.Dog);      //true
var hasHorse = myAnimals.HasFlag(Animals.Horse);  //true
var hasZebra = myAnimals.HasFlag(Animals.Zebra);  //false

回答1:


HasFlag is effectively this:

HasFlag = (GivenFlag & Value) == GivenFlag;

//"Anything" AND 0 == 0  --> always true



回答2:


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




回答3:


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.




回答4:


Well Enum.HasFlags resolves as something like the following:

var hasNone = (myAnimals & Animals.None) == Animals.None

This will always be true for a zero-value-enum-field.




回答5:


From MSDN

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

thisInstance And flag = flag



回答6:


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



来源:https://stackoverflow.com/questions/15436616/hasflags-always-returns-true-for-none-0-value-in-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!