带有 Flags 属性的 C# 枚举
我想知道带有 Flag 属性的枚举是否主要用于按位运算,如果枚举值未定义,为什么编译器不自动生成值。
例如。
[Flags] public enum MyColor { Yellow = 1, Green = 2, Red = 4, Blue = 8 }
如果值 1、2、4、8 在未分配的情况下自动生成,将会很有帮助。想知道您对此的想法。
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 eg.
[Flags] public enum MyColor { Yellow = 1, Green = 2, Red = 4, Blue = 8 }
It would be helpful if the values 1,2,4,8 are autogenerated if they are not assigned. Would like to know your thoughts on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这稍微更容易:
This is a little easier:
他们可能可以,但是对于这种规模的编译器,他们必须考虑实现某些内容所需的时间和资源与潜在的好处,尤其是像这样的语法糖。它只是语法糖,因为你可以手动编写它。
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.
我预计这是因为 FlagsAttribute 实例是与 Enum 一起或之后编译的。也就是说,用属性(如[Flags])装饰对象会导致属性对象的创建,它不会从根本上修改基础对象。
此外,存储的部分信息(用于属性的运行时实例化)是它所引用的实体。实体枚举可能必须在其属性之前编译,因此属性不能影响它引用的实体(在本例中为枚举)。我不知道这个说法是真是假,这只是一个猜测。
最大的收获是属性,如 [Flags],实际上是实体本身,而不是修饰类型的修改。
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.
我认为,除其他外,它会归结为对第一个值的巨大混乱。考虑一下:
当一个类被实例化时,它的所有字段通常都被清零(引用变为空并且值变为零)。但如果第一个值是 1,那么编译器必须以不同于其他任何值的方式处理 Flag 枚举。
因此,考虑到这一点,以及能够将位字段清零非常有用的事实,我们得出的结论是,第一个字段实际上在逻辑上应该为零:
但我想没有多少人会意识到这一点(没有上面的评论)。而且还会出现更棘手的事情:
可能更好地明确地拼写出来以避免大规模混乱! :-)
I think that it, among other things, would boil down to massive confusion of what the first value would be. Consider:
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:
But I guess that not many people would realize this (without the comments above). And more tricky stuff would arise too:
Probably better to spell it out explicitly to avoid massive confusion! :-)