【发布时间】:2013-09-17 07:37:54
【问题描述】:
从 MSDN 文档中,以下两个 sn-ps 是相等的:
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 块。
【问题讨论】:
-
@NickGotch 我看过你的帖子,但老实说我对答案不满意。我想了解为什么在使用一种语法而不是另一种时需要强制转换。
-
我认为在这种情况下你可以只做
x = value,还是我错了?