In C#, the
attribute plays a vital role when defining a set of possible sets of possibilities. These enumerations are usually used together with the positioning of the position to combine and operate multiple options at the same time.
[Flags]
The attribute indicates the combination of an enumeration value, not a single value. This allows:
bit operations: Using bit or operator (| |) can be combined to include multiple options. [Flags]
ToString()
The attribute will not automatically set the enumeration value to the power of 2. In order to ensure the compatibility of the bit operation, you should manually distribute the power of 2 to the value.
Error Declaration:
[Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 }
<确> Correct statement:
[Flags]
<查> Check the combination of the inspection logo
<可> The method can be used to check whether the attribute contains specific signs:
[Flags] public enum MyColors { Yellow, // 0 Green, // 1 Red, // 2 Blue // 3 }
Before .NET 4, you can use the position and the operational symbol (&) to verify the existence of the logo:
[Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 }
<底> The underlying mechanism: position indicates
The value of enumeration is represented in the form of binary. When using the power of 2, the positioning charm operates each bit:
HasFlag
if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { // 允许黄色... }
if ((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { // 允许黄色... }
The
logo usually with 0The above is the detailed content of How Does the C# [Flags] Enum Attribute Work with Bitwise Operations?. For more information, please follow other related articles on the PHP Chinese website!