正确使用Enum的FlagsAttribute

使用步骤

  1. 添加标记[Flags]
  2. 用 2 的幂(即 1、2、4、8 等)定义枚举常量,比如0,1,1<<1,1<<2,1<<3
  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)
{
//...
}
05-14 08:22