为什么我不能设置一个可空INT为NULL if语句三元? [英] Why can't I set a nullable int to null in a ternary if statement?
问题描述
在C#code如下:
int? i;
i = (true ? null : 0);
给我的错误:
有条件的前pression的类型不能
来确定,因为没有
之间的隐式转换'<&空GT;'
和INT
Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int'
应该不是这个有效吗?我在这里丢失怎么办?
Shouldn't this be valid? What am i missing here?
推荐答案
编译器尝试计算右手前pression。 空
是空
和 0
是 INT
的文字,而不是 INT?
。编译器是想告诉你,它不能确定是什么类型的前任pression应评估作为。有之间没有隐式转换空
和 INT
,因此错误消息。
The compiler tries to evaluate the right-hand expression. null
is null
and the 0
is an int
literal, not int?
. The compiler is trying to tell you that it can't determine what type the expression should evaluate as. There's no implicit conversion between null
and int
, hence the error message.
您需要告诉恩pression应该评估为 INT?
的编译器。有 INT?
和 INT
之间,或空$ C之间的隐式转换$ C>和
INT
,所以无论这些应该工作:
You need to tell the compiler that the expression should evaluate as an int?
. There is an implicit conversion between int?
and int
, or between null
and int?
, so either of these should work:
int? x = true ? (int?)null : 0;
int? y = true ? null : (int?)0;
这篇关于为什么我不能设置一个可空INT为NULL if语句三元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!