What does the [Flags] Enum Attribute mean in C#?

前端 未结 13 2276
慢半拍i
慢半拍i 2020-11-21 04:21

From time to time I see an enum like the following:

[Flags]
public enum Options 
{
    None    = 0,
    Option1 = 1,
    Option2 = 2,
    Option3 = 4,
    Op         


        
13条回答
  •  醉酒成梦
    2020-11-21 05:13

    Combining answers https://stackoverflow.com/a/8462/1037948 (declaration via bit-shifting) and https://stackoverflow.com/a/9117/1037948 (using combinations in declaration) you can bit-shift previous values rather than using numbers. Not necessarily recommending it, but just pointing out you can.

    Rather than:

    [Flags]
    public enum Options : byte
    {
        None    = 0,
        One     = 1 << 0,   // 1
        Two     = 1 << 1,   // 2
        Three   = 1 << 2,   // 4
        Four    = 1 << 3,   // 8
    
        // combinations
        OneAndTwo = One | Two,
        OneTwoAndThree = One | Two | Three,
    }
    

    You can declare

    [Flags]
    public enum Options : byte
    {
        None    = 0,
        One     = 1 << 0,       // 1
        // now that value 1 is available, start shifting from there
        Two     = One << 1,     // 2
        Three   = Two << 1,     // 4
        Four    = Three << 1,   // 8
    
        // same combinations
        OneAndTwo = One | Two,
        OneTwoAndThree = One | Two | Three,
    }
    

    Confirming with LinqPad:

    foreach(var e in Enum.GetValues(typeof(Options))) {
        string.Format("{0} = {1}", e.ToString(), (byte)e).Dump();
    }
    

    Results in:

    None = 0
    One = 1
    Two = 2
    OneAndTwo = 3
    Three = 4
    OneTwoAndThree = 7
    Four = 8
    

提交回复
热议问题