Combining Enum Values with Bit-Flags

后端 未结 4 1577
傲寒
傲寒 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:39

    Check out What does the [Flags] Enum Attribute mean in C#? for a more thorough explanation.

    A "safer" way to declare flags is to use bit-shifting to ensure there's no overlap (as mentioned by @DaveOwen's answer) without figuring out the math yourself:

    [Flags]
    public enum MyEnum
    {
        None   = 0,
        First  = 1 << 0,
        Second = 1 << 1,
        Third  = 1 << 2,
        Fourth = 1 << 3
    }
    

    There's also Enum.HasFlag (possibly newer .NET than OP) for checking, rather than Expected & Testing == Expected

提交回复
热议问题