【发布时间】:2018-06-04 03:13:33
【问题描述】:
我正在尝试使用?: Operator 将值分配给一个可为空的布尔变量。
这是可以正常工作的原始代码
bool? result;
var condition = 3;
if (condition == 1)
result = true;
else if (condition == 2)
result = false;
else result = null;
修改代码后报错,上网搜索后修复
// before (error occur)
result = condition == 1 ? true : (condition == 2 ? false : null);
// after (fixed error)
result = condition == 1 ? true : (condition == 2 ? false : (bool?)null);
// *or
result = condition == 1 ? true : (condition == 2 ? (bool?)false : null);
我知道两个表达式必须是同一类型,但是为什么只需要转换一个表达式而不是所有表达式?这让我很困惑。
据我了解,bool and bool? 或 bool? and null 仍应被视为不同类型,但在这种情况下有效。
对此的任何建议将不胜感激。谢谢。
【问题讨论】:
-
看看这个以获得很好的解释。 stackoverflow.com/questions/828950/…