枚举加法与减法和强制转换 [英] Enum addition vs subtraction and casting
问题描述
为什么加法需要强制转换而减法不需要强制转换?请参阅下面的代码以了解我在问什么
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.
推荐答案
好问题 - 我很惊讶第一行和第三行有效.
Good question - I was surprised that the first and third lines worked.
但是,它们在 C# 语言规范中得到支持 - 在第 7.8.4 节中,它讨论了枚举添加:
However, they are supported in the C# language specification - in section 7.8.4, it talks about enumeration addition:
每个枚举类型都隐式地提供了以下预定义的运算符,其中 E 是枚举类型,U 是 E 的基础类型:
Every enumeration type implicitly provides the following pre-defined operators, where E is the enum type and U is the underlying type of E:
E operator +(E x, U y)
E operator +(U x, E y)
在运行时,这些运算符完全按照 (E)((U)x + (U)y) 进行计算
At runtime, these operators are ealuated exactly as (E)((U)x + (U)y)
在第 7.8.5 节中:
And in section 7.8.5:
每个枚举类型都隐式地提供了以下预定义运算符,其中 E 是枚举类型,U 是 E 的基础类型:
Every enumeration type implicitly provides the following predefined operator, where E is the enum type and U is the underlying type of E:
U operator -(E x, E y)
此运算符的计算方式与 (U)((U)x - (U)y))
完全相同.换句话说,运算符计算x
和y
的序数值之间的差值,结果的类型是枚举的底层类型.
This operator is evaluated exactly as (U)((U)x - (U)y))
. In other words, the operator computes the difference between the ordinal values of x
and y
, and the type of the result is the underlying type of the enumeration.
E operator -(E x, U y);
此运算符的计算方式与 (E)((U)x - y)
完全相同.换句话说,运算符从枚举的基础类型中减去一个值,从而产生一个枚举值.
This operator is evaluated exactly as (E)((U)x - y)
. In other words, the operator subtracts a value from the underlying type of the enumeration, yielding a value of the enumeration.
所以这就是编译器的行为方式 - 因为这是 C# 规范所说的:)
So that's why the compiler behaves like that - because it's what the C# spec says to do :)
我不知道存在这些运算符中的任何,而且我从未有意识地看到它们被使用.我怀疑它们存在的原因隐藏在 Eric Lippert 偶尔深入研究的语言设计会议笔记中的某个地方 - 但如果他们因为添加功能而感到遗憾,我也不会感到惊讶.再说一次,也许它们在某些情况下真的很有用:)
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 :)
这篇关于枚举加法与减法和强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!