应用Enum的FlagsAttribute标签能做很多应用,可以使枚举获得多个判断的效果
下面这段代码:
[Flags]
enum WeekDays
{
Monday = 0x1,
Tuesday = 0x2,
Wednesday = 0x4,
Thursday = 0x8,
Friday = 0x10,
Saturday = 0x20,
Sunday = 0x40
}
同样的我们也可以这么写
[Flags]
public enum WeekDays
{
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64
}
这里会用到我们位运算的特性
WeekDays wds = WeekDays.Monday | WeekDays.Sunday | WeekDays.Tuesday;
/* 我们来看看计算过程:
* 或运算:
0000 0001 --星期一 0x1
或 0010 0000 --星期六 0x20
或 0000 0010 --星期二 0x2
= 0010 0011 = 35
*换句话说: 某个位是1就代表了这个位上的值在枚举中存在
*/
Console.WriteLine("这3天组合Int为: " + (int)wds);
/*利用上面规则来判断枚举值中是否包含某个枚举值就轻而易举*/
if ((wds & WeekDays.Monday) != 0)
Console.WriteLine("星期一是其中一天");
if ((wds & WeekDays.Saturday) == 0)
Console.WriteLine("星期六不是其中一天");
//(补充)如果将某个值去掉的话可以按照原来采用这次方式
/* 将星期六从枚举变量中去掉
* 0010 0011
* &1011 1111 (~WeekDays.Monday)取反
* =0000 0011 这样就把星期一去掉啦!
*/
wds = wds & (~WeekDays.Monday);
Console.WriteLine("去掉星期一后的效果: " + wds);
到这里我们看到可以联想到可以用这个枚举来做一些简单的页面权限的判断
比如我们有下面这些权限
[Flags]
public enum Permissions
{
[Description("未設定")]
None = 0,
[Description("建立")]
Create = 1,
[Description("讀取")]
Read = 2,
[Description("更新")]
Update = 4,
[Description("刪除")]
Delete = 8,
[Description("所有功能")]
All = Create | Read | Update | Delete
}
通过下面的判断方法来进行权限判断
Permissions permission = Permissions.None;
permission = permission | Permissions.Create;
MessageBox.Show(permission.ToString());
// Result: Create
permission = permission | Permissions.Read;
permission = permission | Permissions.Update;
MessageBox.Show(permission.ToString());
// Result: Create, Read, Update
permission = (permission & (Permissions.All ^ Permissions.Read));
MessageBox.Show(permission.ToString());
// Result: Create, Update