Common bit operations in C# enumerations
Bitwise operations allow efficient manipulation of individual bits in an enumeration, which is very effective for managing flag values. The following is an example of using C# syntax to perform common operations on an enumeration marked as a [Flags]
attribute:
Set bit
FlagsEnum flags = FlagsEnum.None; flags |= FlagsEnum.Bit4; // 设置位4
Clear bit
flags &= ~FlagsEnum.Bit4; // 清除位4
Toggle position
flags ^= FlagsEnum.Bit4; // 切换位4 (已设置则清除,已清除则设置)
Test position
if ((flags & FlagsEnum.Bit4) != 0) // 测试位4是否已设置
Use extension methods
To simplify bit operations, you can use custom extension methods:
namespace EnumExtensions { public static class EnumerationExtensions { public static bool Has<T>(this Enum type, T value) => ((int)type & (int)value) == (int)value; // ... 其他扩展方法 } }
Using extension methods
SomeType value = SomeType.Grapes; bool isGrapes = value.Is(SomeType.Grapes); // true bool hasGrapes = value.Has(SomeType.Grapes); // true
The above is the detailed content of How Can I Efficiently Use Bitwise Operations on C# Enums?. For more information, please follow other related articles on the PHP Chinese website!