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

前端 未结 13 2278
慢半拍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 04:54

    When working with flags I often declare additional None and All items. These are helpful to check whether all flags are set or no flag is set.

    [Flags] 
    enum SuitsFlags { 
    
        None =     0,
    
        Spades =   1 << 0, 
        Clubs =    1 << 1, 
        Diamonds = 1 << 2, 
        Hearts =   1 << 3,
    
        All =      ~(~0 << 4)
    
    }
    

    Usage:

    Spades | Clubs | Diamonds | Hearts == All  // true
    Spades & Clubs == None  // true
    

     
    Update 2019-10:

    Since C# 7.0 you can use binary literals, which are probably more intuitive to read:

    [Flags] 
    enum SuitsFlags { 
    
        None =     0b0000,
    
        Spades =   0b0001, 
        Clubs =    0b0010, 
        Diamonds = 0b0100, 
        Hearts =   0b1000,
    
        All =      0b1111
    
    }
    

提交回复
热议问题