C# Enums with Flags Attribute

后端 未结 4 1065
难免孤独
难免孤独 2021-02-14 09:54

I was wondering if Enums with Flag attribute are mostly used for Bitwise operations why not the compilers autogenerate the values if the enum values as not defined.

For

4条回答
  •  花落未央
    2021-02-14 10:22

    I think that it, among other things, would boil down to massive confusion of what the first value would be. Consider:

    [Flags]
    public enum MyColor
    {
        Yellow,
        Green,
        Red,
        Blue
     }
    
    public class SomeClass
    {
      public MyColor SomeColor;  // Yellow or undefined by default?
    }
    

    When a class is instantiated all its fields are normally just zeroed out (references become null and values become zero). But if the first value would be one, then the compiler would have to handle Flag enums differently than anything else.

    So, considering this, and also the fact that it is very useful to be able to zero out a bitfield, we arrive to the conclusion that the first field should actually logically be zero:

    [Flags]
    public enum MyColor
    {
        Black,   //0
        Yellow,  //1
        Green,   //2
        Red,     //3
        Blue     //4
    }
    

    But I guess that not many people would realize this (without the comments above). And more tricky stuff would arise too:

    [Flags]
    public enum MyColor
    {
        Black,
        Red,
        Green,
        Blue,
        Magenta = Red | Blue,
        Yellow = Red | Green | Blue,
        SomeOtherColor  // now what would the value of this automatically be?
    }
    

    Probably better to spell it out explicitly to avoid massive confusion! :-)

提交回复
热议问题