How to use Enum with additional options (All, None)

前端 未结 3 1524
栀梦
栀梦 2021-01-05 12:38

I have an enum, which:

  • is included in my class as a property
  • it represents some values from a database table (a couple of types)
  • it is displa
相关标签:
3条回答
  • 2021-01-05 12:41

    Codesleuth comment on another answer made me read the question again and here is an update.

    Consider the use of a flags enumeration if you are going to have multiple combination's. In your case it would mean that selecting any combination of types is a valid input.

    [Flags]
    enum MyTypes
    {
        None = 0,
        One = 1,
        Two = 2,
        Three = 4,
        Four = 8,
        All = One | Two | Three | Four
    }
    

    If the user can only select one type or all the types then use a normal enumeration:

    enum MyType
    {
        None,
        One,
        Two,
        Three,
        Four,
        All
    }
    
    0 讨论(0)
  • 2021-01-05 12:44

    IMHO, it's best to add an 'All' value to your enum like so:

    enum SampleEnum 
    {
        Value1 = 1,
        Value2 = 2,
        Value3 = 4,
        All = Value1 | Value2 | Value3 
    }
    

    This way, you won't have to care about the displayed items in your combobox, and you can react to the selection of that value in your code, if that should be necessary...

    0 讨论(0)
  • 2021-01-05 12:53

    I have another trick, you can check it out at my blog: Enum Trick

    Best practice is to include None or Unknown as Zero(0).

    'All' is a calculated, as a sum of all values.

    [Flags]
    public enum MyTypes
    {
        None = 0,
        One = 1,
        Two = 2,
        Three = 4,
        Four = 8,
        Last,
        All = (Last << 1) - 3,
    }
    

    Now, When you add values, 'All' is updated as well (No change is needed).

    0 讨论(0)
提交回复
热议问题