C# - How to Initialize Flags Enumerations

来源:互联网 发布:米鼠科技淘宝客程序 编辑:程序博客网 时间:2024/09/21 09:06


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,}

1 0
原创粉丝点击