根据MSDN文档,以下两个代码片段是等价的:
bool value;
int x = (value) ? 0 : 1;
而
bool value;
int x;
if (value)
x = 0;
else
x = 1;
很棒,非常好用。简洁高效。
如果我们尝试对可空类型进行这样的操作:int? x = (value.HasValue) ? value.Value : null;
我们会得到一个编译时错误:
The type of conditional expression cannot be determined
because there is no implicit conversion between '{NullableType}' and null.
这个可以成功编译:
int? value;
int? x;
if (value.HasValue)
x = value.Value;
else
x = null;
我理解编译器要求在第一条语句中使用显式转换 (int?)null
。但我不明白的是为什么在 If Else
块中不需要。
x = value
,或者我错了吗? - Alvin Wong