Home >Backend Development >C++ >How Does the C# [Flags] Enum Attribute Enable Bitwise Operations on Enumerations?
The
Putting and enumeration value [Flags]
The attribute itself does not automatically apply the operator. The value of enumeration members must be assigned appropriately to support the bit operation. If the value is not displayed, the value will increase from 0, which will not work properly in the place of computing. The correct enumeration statement
[Flags]
In order to effectively use the enumeration and bit operations, the value of the enumeration member should be the power of 2. For example:
Retrieve a single value
To retrieve the single value from enumerated, you can use the
method or execute the position and operation:<code class="language-csharp">[Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 }</code>
For the previous version of the .NET 4, use the position and operation:
The bottom layer principle [Flags]
HasFlag()
<code class="language-csharp">if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { ... }</code>
<code class="language-csharp">if ((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { ... }</code>
The value can be used as a placeholder without any sign. However, it cannot be used for position and operation, because it always calculates the result of zero. You can use logic comparison to check whether any bit is set:
The above is the detailed content of How Does the C# [Flags] Enum Attribute Enable Bitwise Operations on Enumerations?. For more information, please follow other related articles on the PHP Chinese website!