枚举HasFlag http://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx是你想要使用的
Console.WriteLine("Custodian is in All: {0}", Role.All.HasFlag(Role.Custodian));
只是注意到你的枚举应该像这样定义,其中 Flags 属性和值间隔为 2 的幂
[Flags]
public enum Role
{
NormalUser = 1,
Custodian = 2,
Finance = 4,
SuperUser = Custodian | Finance,
All = Custodian | Finance | NormalUser
}
2 的幂用于标记枚举的原因是 2 的每个幂代表在二进制表示中设置的唯一位:
NormalUser = 1 = 00000001
Custodian = 2 = 00000010
Finance = 4 = 00000100
Other = 8 = 00001000
由于枚举中的每个项目都有一个唯一的位集,因此允许通过设置各自的位来组合它们。
SuperUser = 6 = 00000110 = Custodian + Finance
All = 7 = 00000111 = NormalUser + Custodian + Finance
NormOther = 9 = 00001001 = NormalUser + Other
请注意二进制形式中的每个 1 如何与上一节中为标志设置的位对齐。