Read 《 Pro net 2.0 Windows Forms and custom cortrols in C # You can see the enumeration section and find that multiple values need to be merged in one enumeration. "|" I didn't pay much attention to the operators. Today I thought about why "|" What about it?
In Msdn The following message is displayed: "Use 2 Power (that is 1 , 2 , 4 , 8 . This means that each flag in the enumerated constant of the combination does not overlap ."
So I wrote an example:
[Flagsattribute]
Enum Colors_1
{
Red= 1, Green= 2, Blue= 4, Yellow= 8
} ;
// Test
Private Void Button#click ( Object Sender, eventargs E)
{
Colors_1 color_1 = Colors_1.red | Colors_1.green | Colors_1.blue
| Colors_1.yellow;
String Strresult = Color_1.tostring () + " " + (( Int ) Color_1)
. Tostring ();
MessageBox. Show (strresult );
}
Output result:
Success! 1 + 2 + 4 + 8 = 15 is just equal to 15. Is it a coincidence?
All displayed, easy!
Try again by writing an example:
[Flagsattribute]
Enum Colors_2
{
Red= 1, Green= 2, Blue= 3, Yellow= 4
} ;
// Test
Private Void Button#click ( Object Sender, eventargs E)
{
Colors_2 color_2 = Colors_2.red | Colors_2.green | Colors_2.blue
| Colors_2.yellow;
String Strresult = Color_2.tostring () + " " + (( Int ) Color_2). tostring ();
MessageBox. Show (strresult );
}
Output result:
Dizzy, why not show all the colors?
Success! 3 + 4 = 7: two colors with an enumeration value of 3, 4 are displayed.
What about another example?
// Test
Private Void Button#click ( Object Sender, eventargs E)
{
Colors_1 C = (Colors_1) enum. parse ( Typeof (Colors_1 ), " 7 " );
MessageBox. Show (C. tostring () + " " + (( Int ) C). tostring ());
}
Output result:
It will be automatically converted to the corresponding enumerated value, which is amazing!
Then I add a value whose enumeration is 7:
[Flagsattribute]
Enum Colors_1
{
Red = 1 , Green = 2 , Blue = 4 , Yellow = 8 , Seven = 7
} ;
// Test
Private Void Button#click ( Object Sender, eventargs E)
{
Colors_1 C = (Colors_1) enum. parse ( Typeof (Colors_1 ), " 7 " );
MessageBox. Show (C. tostring () + " " + (( Int ) C). tostring ());
}
output result:
confirmed the sentence msdn , only when the enumerated value is set to ..... in this way, only the overlay is performed. Enumeration automatically determines the current value, if this value exists in the enumeration, of course this value will be displayed. If there is no matching, use addition to check that the numbers add up to this enumeration value, but what if a few numbers add up to this value? I haven't met anyone yet. This is my understanding. I hope you can give me some advice!