为什么运营商<<和>> C# 中的标志枚举没有实现?

发布于 2024-12-10 00:07:28 字数 217 浏览 3 评论 0 原文

我想做这样的事,但我做不到:

[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

这样做是为了什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彼岸花ソ最美的依靠 2024-12-17 00:07:28

枚举本身不是位字段。枚举的全部意义在于抽象出任何潜在的值。使用移位运算符意味着知道这些值是什么。

然而,如果你真的想改变,只需投射:

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

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);
一百个冬季 2024-12-17 00:07:28

[Flag] 枚举可以保存标志的组合。移动组合很少会产生合理的含义

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

您可以强制转换为 int,如果您知道自己在做什么,就可以做您喜欢的事情

注意:如果您确实想使用 SomeEnum 而无需显式强制转换,您可以用像 Pseudo 这样的类型包装它,我在这里定义了它:是否可以包装整数并调用它像整数吗?

请注意,这实际上是一个概念证明,但您可以从那里看到它是如何工作的

A [Flag] enum can hold a combination of flags. 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

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?

Note that it is really a proof of concept thing, but you can see how it would work from there

爱殇璃 2024-12-17 00:07:28

我想说这是因为你“无法将运算符 '<<=' 应用于 'SomeEnum' 和 'int' 类型的操作数”。因此,您必须执行相当不优雅的操作,

var en = SomeEnum.A;

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

即显式执行类型转换,或者,如果您愿意,您可以等待 <<= 实现或等待 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,

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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文