枚举加法与减法和转换
为什么加法需要强制转换而减法无需强制转换就可以工作?请参阅下面的代码以了解我要问的内容
public enum Stuff
{
A = 1,
B = 2,
C = 3
}
var resultSub = Stuff.A - Stuff.B; // Compiles
var resultAdd = Stuff.A + Stuff.B; // Does not compile
var resultAdd2 = (int)Stuff.A + Stuff.B; // Compiles
注意:对于加法和减法,在上面的所有三个示例中,结果是否超出(枚举)范围并不重要。
Why does addition require a cast but subtraction works without a cast? See the code below to understand what I am asking
public enum Stuff
{
A = 1,
B = 2,
C = 3
}
var resultSub = Stuff.A - Stuff.B; // Compiles
var resultAdd = Stuff.A + Stuff.B; // Does not compile
var resultAdd2 = (int)Stuff.A + Stuff.B; // Compiles
note: For both addition and subtraction it does not matter whether result is out of range (of the enum) or not in all three examples above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好问题 - 我很惊讶第一行和第三行有效。
然而,它们在 C# 语言规范中得到支持 - 在第 7.8.4 节中,它讨论了枚举添加:
在第 7.8.5 节中:
这就是为什么编译器会有这样的行为 - 因为这是 C# 规范所说的:)
我不知道这些运算符的存在,而且我从来没有故意看到它们被使用过。我怀疑它们存在的原因埋藏在 Eric Lippert 偶尔深入研究的语言设计会议笔记中的某个地方 - 但如果他们因为添加功能而没有带来什么好处而感到遗憾,我也不会感到惊讶。话又说回来,也许它们在某些情况下确实很有用:)
Good question - I was surprised that the first and third lines worked.
However, they are supported in the C# language specification - in section 7.8.4, it talks about enumeration addition:
And in section 7.8.5:
So that's why the compiler behaves like that - because it's what the C# spec says to do :)
I wasn't aware that any of these operators exist, and I've never knowingly seen them used. I suspect the reasons for their existence are buried somewhere in the language design meeting notes that Eric Lippert occasionally dives into - but I also wouldn't be surprised if they were regretted as adding features for little benefit. Then again, maybe they're really useful in some situations :)
枚举的默认值为 0,1,2... 因此在这种情况下,两个枚举之间的差异将创建另一个枚举(首先比较它们以确保从较大的值中减去较小的值)。
有一半的时间加法会产生一个太高的值而无法成为有效的枚举。
The default values for enums are 0,1,2... so in this case the difference between two enums will create another enum (compare them first to make sure you are subtracting the smaller from the larger).
Half the time addition will create a value too high to be a valid enum.
问题在于,在这种情况下,“+”并不像枚举值之间的加号。
重要的是要理解 + 是运算符,并且没有定义如何将其应用于操作数的规则(Stuff.A 和 Stuff.B)
The problem is that "+" in this context is not like a plus between the values of enumeration.
It is important to understand that + is operator and there are no rules defined how to apply it to operands ( Stuff.A and Stuff.B)