c# - 我可以从三元运算中得到什么类型?

标签 c# ternary-operator

<分区>

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 都可以是 uintint

这是语言规范(可以从 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.

关于c# - 我可以从三元运算中得到什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11040100/

相关文章:

javascript 三元运算符与 if/else 相反

c# - 使用三元运算符了解 C# 编译错误

java - 与等效的 Java 代码相比,C# BitConverter 输出错误的 double 值

c - 为什么用三元运算符初始化数组是非法的?

java - 为什么将三元语句中的空值赋给 boolean 变量会抛出 NPE?

C#、ASP.NET - NullReferenceException - 对象引用未设置为对象的实例

python - Python 中的一行 IF 条件语法

c# - 单元测试异步操作

c# - gridview中的自定义分页

c# - 在 Metro 应用程序中以编程方式设置图像源,图像不会出现