Possible Duplicate:
Why is this code invalid in C#?
Conditional operator cannot cast implicitly?
如果我执行以下操作:
bool someBool = false;
uint value = 0;
这些都很好:
value = (someBool) ? 0 : (uint)1;
value = (someBool) ? (uint)0 : 1;
但这不是:
value = (someBool) ? 0 : 1;
当我可以轻松地说时,为什么我不能使用最后一个:
value = 0;
value = 1;
三元运算符的类型是如何确定的?
您必须将其转换为 uint
以便编译器知道。 0 和 1 都可以是 uint
或 int
。
这是语言规范(可以从 MSDN here 下载):
The second and third operands of the ?: operator control the type of
the conditional expression. Let X and Y be the types of the second and
third operands. Then,
If X and Y are the same type, then this is the type of the conditional
expression.
Otherwise, if an implicit conversion exists from X to Y,
but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion exists from Y to X, but not from
X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.