Home >Backend Development >C++ >How Does the C# [Flags] Enum Attribute Work with Bitwise Operations?
In -depth understanding of [Flags] in C# enumeration attributes
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:
<code class="language-csharp">[Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 }</code>
Correct statement:
[Flags]
Check the combination of the inspection logo
The method can be used to check whether the attribute contains specific signs:
<code class="language-csharp">[Flags] public enum MyColors { Yellow, // 0 Green, // 1 Red, // 2 Blue // 3 }</code>Use bit operator
Before .NET 4, you can use the position and the operational symbol (&) to verify the existence of the logo:
<code class="language-csharp">[Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 }</code>
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
<code class="language-csharp">if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { // 允许黄色... }</code>00000100
<code class="language-csharp">if ((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { // 允许黄色... }</code>
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!