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

前端 未结 13 2288
慢半拍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:12

    I asked recently about something similar.

    If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)

    This allows you to do:

    [Flags]
    public enum PossibleOptions : byte
    {
        None = 0,
        OptionOne = 1,
        OptionTwo = 2,
        OptionThree = 4,
        OptionFour = 8,
    
        //combinations can be in the enum too
        OptionOneAndTwo = OptionOne | OptionTwo,
        OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree,
        ...
    }
    

    Then you can do:

    PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree 
    
    if( opt.IsSet( PossibleOptions.OptionOne ) ) {
        //optionOne is one of those set
    }
    

    I find this easier to read than the most ways of checking the included flags.

提交回复
热议问题