C# Enums with Flags Attribute

后端 未结 4 1056
难免孤独
难免孤独 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! :-)

    0 讨论(0)
  • 2021-02-14 10:33

    They probably could, but with a compiler of this size they have to take into consideration the time and resources required to implement something vs the potential benefit, especially with syntactic sugar like this. And it is just syntactic sugar because you can write it manually.

    0 讨论(0)
  • 2021-02-14 10:36

    This is a little easier:

    [Flags]
    public enum MyColor
    {
        Yellow = 1<<0,
        Green = 1<<1,
        Red = 1<<2,
        Blue = 1<<3
    }
    
    0 讨论(0)
  • I expect it is because the FlagsAttribute instance is being compiled alongside, or after, the Enum. That is to say decorating an object with an atribute (like [Flags]) causes the creation of an attribute object, it doesn't modify the base object in a fundamental way.

    Also, part of the information stored (for run-time instantiation of the attribute) is the entity to which it refers. It may be that the entity enum must be compiled before its attributes, so an attribute couldn't affect the entity it refers to (in this case enum). I don't know this statement to be true, it's just a guess.

    The big take-away is the attributes, like [Flags], are actually entities themselves and not modifications of the decorated type.

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