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

前端 未结 7 925
你的背包
你的背包 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:31

    This is really more of a comment, but since that wouldn't support formatting, I just wanted to include a method I've employed for setting up flag enumerations:

    [Flags]
    public enum FlagTest
    {
        None = 0,
        Read = 1,
        Write = Read * 2,
        Delete = Write * 2,
        ReadWrite = Read|Write
    }
    

    I find this approach especially helpful during development in the case where you like to maintain your flags in alphabetical order. If you determine you need to add a new flag value, you can just insert it alphabetically and the only value you have to change is the one it now precedes.

    Note, however, that once a solution is published to any production system (especially if the enum is exposed without a tight coupling, such as over a web service), then it is highly advisable against changing any existing value within the enum.

    0 讨论(0)
提交回复
热议问题