Home >Backend Development >C++ >How to Perform Bitwise Operations on Flags Enums in C#?
Bitwise operations of [Flags] enumeration in C#
When using flag enumerations, it is crucial to master bit operations to seamlessly manage and manipulate individual bits within the enumeration value. This cheat sheet is intended to provide a brief overview of common bit operations in C#.
Set specific bits
To set a specific bit in the [Flags] enumeration, use the bitwise OR operator (|). Consider the following example:
<code class="language-csharp">FlagsEnum flags = FlagsEnum.None; flags |= FlagsEnum.Bit4; // 设置位 4</code>
Remove specific bits
To remove a specific bit, use the bitwise AND operator and the negation of the bit. Here is an example:
<code class="language-csharp">if ((flags & ~FlagsEnum.Bit4) == 0) { // 已移除位 4 }</code>
Toggle specific bits
To switch a specific bit to its opposite value, use the bitwise XOR operator (^).
<code class="language-csharp">flags ^= FlagsEnum.Bit4; // 切换位 4</code>
Check if a specific bit is set
To determine whether a specific bit is set, use the bitwise AND operator and then compare.
<code class="language-csharp">if ((flags & FlagsEnum.Bit4) == FlagsEnum.Bit4) { // 设置了位 4 }</code>
Additional extension methods
Extending the System.Enum class with custom methods can further simplify bit operations. Consider the following extension:
<code class="language-csharp">public static class EnumExtensions { public static bool Has<T>(this Enum type, T value) => (((int)(object)type & (int)(object)value) == (int)(object)value); public static T Add<T>(this Enum type, T value) => (T)(object)(((int)(object)type | (int)(object)value)); public static T Remove<T>(this Enum type, T value) => (T)(object)(((int)(object)type & ~(int)(object)value)); }</code>
These methods provide convenient shortcuts for bitwise operations:
<code class="language-csharp">SomeType value = SomeType.Grapes; value.Has(SomeType.Grapes); // true value = value.Add(SomeType.Oranges); value.Has(SomeType.Oranges); // true value = value.Remove(SomeType.Grapes); value.Has(SomeType.Grapes); // false</code>
The above is the detailed content of How to Perform Bitwise Operations on Flags Enums in C#?. For more information, please follow other related articles on the PHP Chinese website!