The most common way to initialize flags is to use hexadecimal literals. This is how Microsoft and most C# developers do it:
[Flags] public enum DaysOfTheWeek { None = 0, Sunday = 0x01, Monday = 0x02, Tuesday = 0x04, Wednesday = 0x08, Thursday = 0x10, Friday = 0x20, Saturday = 0x40, }
An even better method might be to use binary literals such as 0b0001, 0b0010, 0b0100, 0b1000, etc., but C# does not provide binary literals. However, you can simulate a binary literal with the bit shift
operator. This method has the advantage that the numbers visually increase by 1, so it’s very easy to spot errors and see which bit is set for each flag. Note that this method does not affect program performance because the flag values are calculated at
compile time.
[Flags] public enum DaysOfTheWeek { None = 0, Sunday = 1 << 0, Monday = 1 << 1, Tuesday = 1 << 2, Wednesday = 1 << 3, Thursday = 1 << 4, Friday = 1 << 5, Saturday = 1 << 6, }
时间: 2024-10-06 17:52:45