今天我在CodeGolf StackExchange做了另一个Codegolf挑战,我试图这样做:
SomeEnum = SomeCondition ? 1 : 2;
但这告诉我Cannot convert source type 'int' to target type 'SomeEnum'
,所以我尝试了这个:
SomeEnum = SomeCondition ? (SomeEnum)1 : (SomeEnum)2;
这解决了我的问题,但令我惊讶的是,这里的第一个演员据说是多余的。我的问题是:为什么我只需要将最后一个整数转换为SomeEnum
?
条件运算符的规则是 (C# 规范 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.
通常,枚举和整数之间在任一方向上都没有隐式转换。
那么,为什么你的代码可以工作呢?因为在您的实际代码中,第一个值是 0
,而不是 1
。因此,我们得到了一种可以将整数隐式转换为枚举的情况(C# 规范 6.1.3(:
隐式枚举转换允许将十进制-整数-文本 0 转换为任何枚举类型以及其基础类型为枚举类型的任何可为 null 的类型...
你也可以这样写
SomeEnum = (SomeEnum)(SomeCondition ? 1 : 2);
左侧的SomeEnum总是期望结果为"SomeEnum"。所以我们需要转换它。
要将三元运算符的结果绑定到SomeEnum
,两个分支的结果(真和假(应该能够隐式转换为SomeEnum
,但默认情况下没有隐式强制转换运算符来定义int
C# 中的enum
类型。如果有隐式运算符,这将是有效的方案。
我希望这能解释这种情况。
编译时没有任何警告:
SomeEnum SomeEnum = (true) ? (SomeEnum)1 : (SomeEnum)2;
但是你应该为枚举变量分配一个枚举值:
SomeEnum SomeEnum = (true) ? SomeEnum.First : SomeEnum.Second;
public enum SomeEnum : byte
{
First = 1,
Second = 2
}
以下内容不应编译:
SomeEnum SomeEnum = (true) ? (SomeEnum)1 : 2; //THIS WON'T COMPILE!
。除非第一个值为 0:
SomeEnum SomeEnum = (true) ? 0 : 2;