枚举除VS减法和铸造 [英] Enum addition vs subtraction and casting
问题描述
为什么除了需要强制,但减法作品,未经强制转换?请参见下面的code明白我在问
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:
每个枚举类型都隐式提供下列pre定义运算符,其中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)
在运行时,这些运营商完全ealuated为(E)((U)x +(U)Y)
At runtime, these operators are ealuated exactly as (E)((U)x + (U)y)
和第7.8.5:
每个枚举类型都隐式提供下列predefined运营商,其中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
和是
,以及结果的类型的序数值之间的差是枚举的基础类型。
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 :)
我不知道的任意的这些运营商的存在,我从来没有故意见过他们使用。我怀疑的原因,他们的存在是介于语言设计会议埋指出,埃里克利珀偶尔潜入 - 但我也不会感到惊讶,如果他们感到遗憾的是增加功能没有什么好处。再说,也许他们的真正的在某些情况下非常有用:)
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 :)
这篇关于枚举除VS减法和铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!