Difference in testing for Enum Flags?
Was looking at another question, and was curious if there's any difference at all (in operation or performance) between these two.
Given:
[Flags]
enum TransportModes
{
开发者_运维百科 None = 0,
Bus = 1,
Train = 2,
Plane = 4
}
And a variable
var trip = TransportModes.Bus | TransportModes.Train;
if((trip & TransportModes.Bus) == TransportModes.Bus) ...
if((trip & TransportModes.Bus)) != 0) ...
I know what they do bit wise, and I know that HasFlag replaces them. But Jon Skeet recommends one, and the MSDN docs recommend another.
Your second option will return true, if the values you gave your enum values are not powers of two. The first option doesn't have this problem.
Example:
[Flags]
enum TransportModes
{
None = 0,
Bus = 1,
Train = 2,
Plane = 5
}
var trip = TransportModes.Bus | TransportModes.Train;
if((trip & TransportModes.Plane) != 0)
// will be executed
if((trip & TransportModes.Plane) == TransportModes.Plane)
// won't be executed
Explanation:
trip & TransportModes.Plane
is 1 which is apparently != 0
, but not equal to TransportModes.Plane
which has a value of 5.
However, if you don't use powers of two for the values of a flag enum, you most likely have bigger issues. Think about what happens, if Plane
would have the value 3: You couldn't tell Bus | Train
and Plane
apart...
If bus
is not a power of two (if it has multiple bits set), and trip
has only some of those bits set, (trip & bus) == bus
will be false, but (trip & bus)) != 0
will be true.
精彩评论