Why do enum permissions often have 0, 1, 2, 4 values?

前端 未结 7 947
你的背包
你的背包 2020-12-04 05:53

Why are people always using enum values like 0, 1, 2, 4, 8 and not 0, 1, 2, 3, 4?

Has this something to do with bit operations, etc.?

7条回答
  •  执念已碎
    2020-12-04 06:18

    Because these values represent unique bit locations in binary:

    1 == binary 00000001
    2 == binary 00000010
    4 == binary 00000100
    

    etc., so

    1 | 2 == binary 00000011
    

    EDIT:

    3 == binary 00000011
    

    3 in binary is represented by a value of 1 in both the ones place and the twos place. It is actually the same as the value 1 | 2. So when you are trying to use the binary places as flags to represent some state, 3 isn't usually meaningful (unless there is a logical value that actually is the combination of the two)

    For further clarification, you might want to extend your example enum as follows:

    [Flags]
    public Enum Permissions
    {
      None = 0,   // Binary 0000000
      Read = 1,   // Binary 0000001
      Write = 2,  // Binary 0000010
      Delete = 4, // Binary 0000100
      All = 7,    // Binary 0000111
    }
    

    Therefore in I have Permissions.All, I also implicitly have Permissions.Read, Permissions.Write, and Permissions.Delete

提交回复
热议问题