为什么运营商<<和>> C# 中的标志枚举没有实现?
我想做这样的事,但我做不到:
[Flags]
enum SomeEnum : int
{
None = 0,
A,
B,
C
}
SomeEnum en = SomeEnum.A;
en <<= 1; //Expect en == SomeEnum.B but I recieve an error here
这样做是为了什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
枚举本身不是位字段。枚举的全部意义在于抽象出任何潜在的值。使用移位运算符意味着知道这些值是什么。
然而,如果你真的想改变,只需投射:
Enums are not bit fields in themselves. The whole point of enums is to abstract away any underlying values. Using shift operators implies knowing what these values are.
However, if you really want to shift, just cast:
[Flag] 枚举可以保存标志的组合。移动组合很少会产生合理的含义
您可以强制转换为 int,如果您知道自己在做什么,就可以做您喜欢的事情
注意:如果您确实想使用
SomeEnum
而无需显式强制转换,您可以用像Pseudo
这样的类型包装它,我在这里定义了它:是否可以包装整数并调用它像整数吗?请注意,这实际上是一个概念证明,但您可以从那里看到它是如何工作的
A [Flag] enum can hold a combination of flags. Shifting a combination will rarely result in sensible meaning
You can cast to int, and do what you like if you know what you're doing
NOTE: if you really want to use
SomeEnum
without explicitely casting, you could wrap it with a type likePseudo<SomeEnum>
which I defined here: Is it possible to wrap integer and call it like integer?Note that it is really a proof of concept thing, but you can see how it would work from there
我想说这是因为你“无法将运算符 '<<=' 应用于 'SomeEnum' 和 'int' 类型的操作数”。因此,您必须执行相当不优雅的操作,
即显式执行类型转换,或者,如果您愿意,您可以等待
<<=
实现或等待Enum
code> 隐式转换为 int 运算符来实现,这两种情况似乎都不太可能,这不是应该偶然完成的事情。您可以编写自己的扩展方法来实现相同的目的,但我认为这需要使用一些反射来处理
Enum
的不同基本类型I would say that this is because you "Cannot apply operator '<<=' to operands of type 'SomeEnum' and 'int'". So instead you have to do the rather less elegant,
Which explicitly does the type conversion or, if you prefer you can wait for
<<=
to be implmented or for theEnum
implicit cast to int operator to implemented, Neither of which seems likely, its not somthing that should be done by accident.You could write you own extension method to achieve the same but I think that would need to use some reflection to handle the different base types of
Enum