简体   繁体   English

为什么在C#中没有为标志枚举实现运算符<<和>>?

[英]Why operators << and >> are not realized for flag enums in C#?

I want to do something like this, but I can't: 我想做这样的事情,但是我不能:

[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

For what It has been done so? 这样做是为了什么?

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: 但是,如果您确实要转移,请进行强制转换:

en = (SomeEnum)((int)en << 1);

A [Flag] enum can hold a combination of flags. [Flag]枚举可以包含标志的组合。 Shifting a combination will rarely result in sensible meaning 转移组合很少会产生有意义的含义

SomeEnum en = SomeEnum.A | SomeEnum.B;
en <<= 1; //Expect what?

You can cast to int, and do what you like if you know what you're doing 您可以将其转换为int,如果知道自己在做什么,可以执行自己喜欢的操作

NOTE: if you really want to use SomeEnum without explicitely casting, you could wrap it with a type like Pseudo<SomeEnum> which I defined here: Is it possible to wrap integer and call it like integer? 注意:如果您真的想使用SomeEnum而不显式地进行强制转换,则可以使用我在此处定义的Pseudo<SomeEnum>类的类型包装它: 是否可以包装整数并像整数一样调用它?

Note that it is really a proof of concept thing, but you can see how it would work from there 请注意,这确实是概念证明,但您可以从那里看到它的工作原理。

I would say that this is because you "Cannot apply operator '<<=' to operands of type 'SomeEnum' and 'int'". 我会说这是因为您“无法将运算符'<< ='应用于'SomeEnum'和'int'类型的操作数”。 So instead you have to do the rather less elegant, 因此,您必须做得不太优雅,

var en = SomeEnum.A;

en = (SomeEnum)((int)en << 1);

Which explicitly does the type conversion or, if you prefer you can wait for <<= to be implmented or for the Enum implicit cast to int operator to implemented, Neither of which seems likely, its not somthing that should be done by accident. 类型转换是显式进行的,或者,如果您愿意,可以等待<<=实现,或者等待Enum隐式强制转换为int运算符的实现,这似乎都不可行,这并不是偶然的。

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 您可以编写自己的扩展方法来实现相同的功能,但我认为这需要使用一些反射来处理Enum的不同基本类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM