When defining enumeration in C#, if enumeration represents the set of values rather than a single value, you can use the [Flags] property. This attribute is particularly useful in the enumeration of the use operator.
In contrast to the universal misunderstanding, the [Flags] attribute provides a more readable representation form through the method. The enumeration marked with [Flags] will output its value, and the value is displayed in the form of a sign of a comma separation. As shown below:
.ToString()
The power value of 2
enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } ... var str1 = (Suits.Spades | Suits.Diamonds).ToString(); // "5" var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString(); // "Spades, Diamonds"
It must be emphasized that the [Flags] attribute does not automatically assign the power value of 2 to enumeration. If the value of the value is skipped, the holding of the operation in the position is incorrect, because the default value increases from 0. <确> The correct statement:
<取> Get different values:
To retrieve the different values in the enumeration attributes, you can use multiple methods:[Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 }
Use <.> (. Net 4 and higher versions available):
.HasFlag()
if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { // Yellow is allowed... }
[Flags] Properties are allowed to operate binary values by operating by bit computing. By using the power value of 2 as an enumeration value, the underlying binary of the value means that it allows efficient and meaningful calculations.
if ((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { // Yellow is allowed... }
For more information and resources about the [Flags] attributes, its usage and design mode, see the MSDN documentation.
The above is the detailed content of How Does the C# [Flags] Enum Attribute Enhance Bitwise Operations and Enumeration Readability?. For more information, please follow other related articles on the PHP Chinese website!