Met*_*iem 4 c# enums casting ternary
今天我在Codegolf StackExchange上做了另一个Codegolf挑战,我试着这样做:
SomeEnum = SomeCondition ? 1 : 2;
Run Code Online (Sandbox Code Playgroud)
但是这告诉我Cannot convert source type 'int' to target type 'SomeEnum',所以我尝试了这个:
SomeEnum = SomeCondition ? (SomeEnum)1 : (SomeEnum)2;
Run Code Online (Sandbox Code Playgroud)
这解决了我的问题,但令我惊讶的是,这里的第一次演员据说是多余的.我的问题是:为什么我只需要将最后一个整数转换为 SomeEnum?
条件运算符的规则是(C#Spec 7.14):
• If x has type X and y has type Y then
o If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
o If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
o Otherwise, no expression type can be determined, and a compile-time error occurs.
Run Code Online (Sandbox Code Playgroud)
通常,枚举和整数之间的任何一个方向都没有隐式转换.
那么,为什么你的代码有效?因为在您的实际代码中,第一个值0不是1.因此我们得到一个整数可以隐式转换为枚举的情况(C#Spec 6.1.3):
隐式枚举转换允许将decimal-integer-literal 0转换为任何枚举类型和任何可以为其类型为枚举类型的nullable 类型 ...