Enumeration Using Attribute Flags

suppose we have enumone that has FlagsAttribute.

[Flags]
enum CarOptions
{
  Sunroof = 1,
  Spoiler = 2,
  TintedWindow = 4
}

It can be used easily. now suppose this

[Flags]
enum CarOptions
{
  SunroofElectrical,
  SunroofMechanical,
  Spoiler,
  TintedWindowBlack,
  TintedWindowPurple
}

of course, this is syntactically incorrect. but a car cannot have a mechanical and electric sunroof at the same time or have black and purple tinted wallpapers. The question is: is there a mechanism for implementing the Flags enumeration that cannot have some attributes at the same time?

+3
source share
4 answers

. - . , . , , , :

class CarOptions
{
    public SunroofKind Sunroof { get; set; }
    public SpoilerKind Spoiler { get; set; }
    public TintedWindowKind TintedWindow { get; set; }
    // Note that I split this into two enums - the kind of tinted window
    // (UV-resistant option too maybe?) and color might be different.
    // This is just an example of how such option composition can be done.
    public TintedWindowColor TintedWindowColor { get; set; }

    // In this class, you can also implement additional logic, such as
    // "cannot have spoiler on diesel engine models" and whatever may be required.
}

enum SunroofKind
{
    None,
    Electrical,
    Mechanical
}

enum SpoilerKind
{
    None,
    Standard
}

enum TintedWindowKind
{
    None,
    Standard
}

enum TintedWindowColor
{
    Black,
    Blue
}

, . โ€‹โ€‹ - , , . (, , , , ).

- / .

+2

, , Sunroofs TindedWindows.

+3

You have two options, as I see:

1) Do not use enum. Use a different mechanism to configure parameters that come in combinations that conflict with each other.

2) Define invalid combinations and check them when setting flags:

[flags]
enum CarOptions
{
  SunroofElectrical = 1,
  SunroofMechanical = 2,
  Spoiler           = 4,
  TintedWindowBlack = 8,
  TintedWindowPurple= 16,
  // bad combos
  BadSunroof        = 3,
  BadWindowColor    = 24
}

CarOptions opt = CarOptions.SunroofElectrical | CarOptions.SunroofMechanical;
if(opt & BadSunroof)
{
}
+1
source

You can use one bit of flags to indicate the function present, and the other to indicate the โ€œtasteโ€ of the function:

[Flags]
enum CarOptions
{
  Sunroof = 1,
  SunroofElectrical = 1,
  SunroofMechanical = 3,
  Spoiler = 4,
  TintedWindow = 8,
  TintedWindowBlack = 8,
  TintedWindowPurple = 24
}

Then it is impossible to have both "tastes" together.

+1
source

Source: https://habr.com/ru/post/1784496/


All Articles