Home >Backend Development >C++ >How Does the C# [Flags] Enum Attribute Enable Bitwise Operations on Enumerations?

How Does the C# [Flags] Enum Attribute Enable Bitwise Operations on Enumerations?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-02-02 14:46:09247browse

How Does the C# [Flags] Enum Attribute Enable Bitwise Operations on Enumerations?

Understand [Flags] in C#enumerated attributes

The attribute of C#is used to define the enumeration that represents multiple possible values, not a single value. The lifts using this attribute can be used together with the bit operation symbol, so as to combine and analyze multiple values ​​in a variable.

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()

The reason for using the power of 2 in enumeration is that they directly convert to binary representations. When using the position or the combination of the operation, the generated binary value reflects the label of enable. Similarly, a single logo is allowed to be tested according to the position and operation.
<code class="language-csharp">if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { ... }</code>

None value

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn