正确使用Enum的FlagsAttribute
FlagsAttribute 标志枚举对象的值可以包括多个枚举成员,每个成员代表枚举值中的一个位域
使用步骤
- 添加标记
[Flags]
- 用 2 的幂(即 1、2、4、8 等)定义枚举常量,比如0,1,1<<1,1<<2,1<<3
- 标记
[Flags]
的枚举项之间可以进行NOT,OR,AND,XOR操作
例子1
[Flags]public enum DaysOfWeek{ Sunday = 1, Monday = 1 << 1, Tuesday = 1 << 2, Wednesday = 1 << 3, Thursday = 1 << 4, Friday = 1 << 5, Saturday = 1 << 6,} var workDays1 = DaysOfWeek.Monday | DaysOfWeek.Tuesday | DaysOfWeek.Thursday | DaysOfWeek.Thursday | DaysOfWeek.Friday; var workDays2 = DaysOfWeek.Friday | DaysOfWeek.Saturday | DaysOfWeek.Sunday; ~workDays1 //DaysOfWeek.Saturday,DaysOfWeek.Sunday workDays1 ^workDays2 //DaysOfWeek.Monday, DaysOfWeek.Tuesday,DaysOfWeek.Thursday, //DaysOfWeek.Thursday,DaysOfWeek.Saturday, DaysOfWeek.Sunday workDays1&DaysOfWeek.Monday //DaysOfWeek.Monday
例子2
//判断是否包含某项 //.net4.0新增 if (workDays1.HasFlag(DaysOfWeek.Monday)) { //... } //4.0以前的版本 if ((workDays1 & DaysOfWeek.Monday) == DaysOfWeek.Monday) { //... }