How do I retrieve a value from a [Flag] enum property?
This question already has an answer here:
First of all, flags must have a None = 0
value, because otherwise there's no way to represent a 0
mask (ie no value).
Once you've fixed it, you can check if some enumeration value is in some given flag using Enum.HasFlag
or the bit-wise &
operator:
Level.HasFlag(LogLevel.Pages);
...or:
(Level & LogLevel.Pages) == LogLevel.Pages
Finally, when you implement a flags enumeration, usually enumeration identifier is expressed in plural. In your case, you should refactor LogLevel
to LogLevels
.
Why &
?
Each enumeration value represents a bit in a complete mask. For example, None
would be 0, but it could be also represented as 0, 0, 0
where each 0
is one of possible enumeration values in LogLevels
. When you provide a mask like LogLevels.Pages | LogLevels.Methods
LogLevels.Pages | LogLevels.Methods
, then the mask is 1, 1, 0
.
In order to check if Pages
is within the mask, you use a logical AND comparing the mask with one of possible enumeration values:
1, 1, 0 (LogLevels.Pages | LogLevels.Methods)
1, 0, 0 AND (LogLevels.Pages)
--------
1, 0, 0
The whole AND is like isolating the tested enumeration value. If the resulting mask equals the enumeration value, then the mask contains the enumeration value.
Some OP concern
OP said in some comment:
Just a quick question on zero value. here it states that You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. Does that mean if I have a 0 value I cannot use & and must use HasFlag?
None
(ie 0
) won't be a member of a mask, because 0 doesn't exist. When you produce a mask you're using the OR |
logical operator, which is, at the end of the day, an addition.
Think about 1 + 0 == 1
. Would you think checking if 0
is within 1
is ever possible?
Actually, the None = 0
value is required to be able to represent and empty mask.
Finally, HasFlag
does the AND
for you, it's not a magical solution, but a more readable and encapsulated way of performing the so-called AND
.
喜欢这个
if (Level.HasFlag(LogLevel.Pages))
{
//todo
}
链接地址: http://www.djcxy.com/p/54432.html
上一篇: c#check enum包含在选项中
下一篇: 如何从[Flag]枚举属性中检索值?