Combining Enum Values with Bit-Flags

后端 未结 4 1579
傲寒
傲寒 2021-02-13 04:43

I have this scenario where user has its role

NormalUser
Custodian
Finance

both Custodian and Finance is a Super

4条回答
  •  春和景丽
    2021-02-13 05:42

    Enum.HasFlag is what you want to use

    Console.WriteLine("Custodian is in All: {0}", Role.All.HasFlag(Role.Custodian));
    

    Just noticed that your enum should be defined like this with the Flags attribute and values spaced out by powers of 2

    [Flags]
    public enum Role
    {
        NormalUser = 1,
        Custodian = 2,
        Finance = 4,
        SuperUser = Custodian | Finance,
        All = Custodian | Finance | NormalUser
    }
    

    The reason powers of 2 are used for flagged enums is that each power of 2 represents a unique bit being set in the binary representation:

    NormalUser = 1 = 00000001
    Custodian  = 2 = 00000010
    Finance    = 4 = 00000100
    Other      = 8 = 00001000
    

    Because each item in the enum has a unique bit set this allows them to be combined by setting their respective bits.

    SuperUser  = 6 = 00000110 = Custodian + Finance
    All        = 7 = 00000111 = NormalUser + Custodian + Finance
    NormOther  = 9 = 00001001 = NormalUser + Other
    

    Notice how each 1 in the binary form lines up with the bit set for the flag in the section above.

提交回复
热议问题