当枚举用来表示一组位集合而不是单个值的时候,我们就需要用到位枚举。在定义位枚举类型时,通常需要显示的为每个枚举成员分配一个数值,并且还可以定义一些组合值。最后还需要给枚举加上[Flags]特性标记,如
[Flags]
public enum Actions
{
None = 0,
Read = 0x0001,
Write = 0x0002,
ReadWrite = Actions.Read | Actions.Write,
Delete = 0x0004,
Query = 0x0008,
All= 0x000F
}
有时候枚举的成员多了之后,用十进制数或者十六进制数表示枚举成员数值需要进行简单计算,比较麻烦。所以枚举成员比较多的时候可以试试下面两种方式
在C# 7.0后可以通过二进制数值进行表示
[Flags]
public enum Actions
{
None = 0,
Read = 0b0001,
Write = 0b0010,
ReadWrite = Actions.Read | Actions.Write,
Delete = 0b0100,
Query = 0b1000,
All=0b1111
}
还可以通过移位运算表示,通过将1左移对应的位数即可
[Flags]
public enum Actions
{
None = 0,
Read = 1 << 0,
Write = 1 << 1,
ReadWrite = Actions.Read | Actions.Write,
Delete = 1 << 2,
Query = 1 << 3,
All = ~(~0 << 4)
}