为什么有些值在方括号中,1<< 1< 1:
public enum PrivilegeFlags : int
{
None = 0,
[EnumMember(Value = "Agent")]
Agent = 1 << 0,
[EnumMember(Value = "Campaign")]
Campaign = 1 << 1,
[EnumMember(Value = "BlackList")]
BlackList= 1 << 2,
All = (1 << 3) - 1
}
感谢。
答案 0 :(得分:2)
答案 1 :(得分:1)
似乎Enum
旨在创建标志。如果将枚举值转换为二进制值,则可以更清楚地看到它:
public enum PrivilegeFlags : int
{
None = 0, //0000 0000
[EnumMember(Value = "Agent")]
Agent = 1 << 0, //0000 0001
[EnumMember(Value = "Campaign")]
Campaign = 1 << 1, //0000 0010
[EnumMember(Value = "BlackList")]
BlackList= 1 << 2, //0000 0100
All = (1 << 3) - 1 //0000 0111
}
和EnumMember
是分配给PrivilegeFlags
enum
成员的属性。
您不需要声明enum
如下所示,因为以下是等效的枚举:
public enum PrivilegeFlags : int
{
None = 0, //0000 0000
[EnumMember(Value = "Agent")]
Agent = 1, //0000 0001
[EnumMember(Value = "Campaign")]
Campaign = 2, //0000 0010
[EnumMember(Value = "BlackList")]
BlackList= 4, //0000 0100
All = 7 //0000 0111
}
1 << 1
表示您的值为1
,而您将1
的二进制左移值设为值1
。从二进制层面可以清楚地看到:
0000 0001 //1 in binary
--------- << 1 shift left by 1
0000 0010 //note the binary shift, now this is actually 2
使用指定的左移<<
的好处是使标志创建具有增量编号:0, 1, 2, 3, 4, ...
等,而不是具有2^n
和{{1]模式的编号}:0