C # .NET: if ((e.State & ListViewItemStates.Selected)! = 0) <- What does this mean?

In the standard MSN code, there is a line in ListView - Ownerdraw - DrawItem:

 if ((e.State & ListViewItemStates.Selected) != 0) { //Draw the selected background } 

Apparently, is this a bitwise comparison for the state? Why bitwise? The following does not work:

 if (e.State == ListViewItemStates.Selected) { //Doesn't work ?? } 

Why does this comparison not work? Is it just a standard enum ?? I'm a little confused.

+4
source share
5 answers

This is not a standard Enum - it is decorated with FlagsAttribute , making it a bitmask. See the MSDN FlagsAttribute for details .

The first example checks to see if any of the flags are set, as you correctly interpreted. Flags are usually combined using | (although + and ^ are also safe for a properly defined attribute without overlapping).

+9
source
+4
source

You can also use this:

 if (e.State.HasFlag(ListViewItemStates.Selected)) 

to check if an item is selected.

+3
source

The state value is an enumeration of the flag - this means that different bits in it mean different things, and you can combine them to tell you a few things about the state. for instance

 [Flags] public enum States { Selected = 1; OnScreen = 2; Purple = 4; } 

So, if you want to see that something is selected, you cannot just compare it with the selected one (see if it has an int 1 value), since it can be selected both on the screen and on the screen (and it will have an int value of 3). Performing a bitwise comparison, you check to see if the Selected check box is selected, ignoring the meaning of other flags.

+1
source

ListViewItemStates is a Flag enumeration: the ListViewItemStates variable can be a combination of values. Example: Focused and Validated

If you use equality, for example e.State == ListViewItemStates.Selected , to determine if an item is selected, you will be able to detect the case when the value is only "Selected", but you will skip the case when this value is a state composition.

Bitwise operation allows you to check the value yourself.

Hope this helps

+1
source

Source: https://habr.com/ru/post/1310246/


All Articles