C# Enum 需要三元转换吗?

C# Enum requires cast in ternary?

今天我在 Codegolf StackExchange 进行了另一个 Codegolf 挑战,我尝试这样做:

SomeEnum = SomeCondition ? 1 : 2;

但这告诉我 Cannot convert source type 'int' to target type 'SomeEnum',所以我尝试了这个:

SomeEnum = SomeCondition ? (SomeEnum)1 : (SomeEnum)2;

然后解决了我的问题,但令我惊讶的是,这里的第一个演员据说是多余的。我的问题是:为什么我只需要将最后一个整数转换为 SomeEnum?

要将三元运算符的结果绑定到 SomeEnum,两个分支(true 和 false)的结果应该能够隐式转换SomeEnum,但在 c# 中没有为 enum 类型定义的 隐式转换运算符 默认为 int。如果有隐式运算符,这将是有效的场景。

我希望这能说明情况。

编译时没有任何警告:

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;

你也可以这样写

SomeEnum = (SomeEnum)(SomeCondition ? 1 : 2);

左侧的 SomeEnum 始终期望结果为 '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):

An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type...