- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
为什么不能编译?
int? number = true ? 5 : null;
Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>
最佳答案
规范 (§7.14) 说对于条件表达式 b ? x : y
,存在三种可能性,x
和 y
都具有类型和某些良好条件 满足,x
和 y
中只有一个具有类型并且满足某些良好条件,或发生编译时错误。这里的“一定的好条件”是指一定的转换是可能的,我们将在下面详细介绍。
现在,让我们转向规范的相关部分:
If only one of
x
andy
has a type, and bothx
andy
are implicitly convertible to that type, then that is the type of the conditional expression.
这里的问题是
int? number = true ? 5 : null;
只有一个条件结果有类型。这里 x
是一个 int
字面量,而 y
是 null
,不 和 null
类型不能隐式转换为 int
1。因此,不满足“某些良好条件”,就会出现编译时错误。
有两种解决方法:
int? number = true ? (int?)5 : null;
这里我们仍然处于只有 x
和 y
之一有类型的情况。请注意,null
仍然 没有类型,但编译器对此不会有任何问题,因为 (int?)5
和 null
都可以隐式转换为 int?
(§6.1.4 和 §6.1.5)。
另一种方式显然是:
int? number = true ? 5 : (int?)null;
但现在我们必须阅读规范中的一个不同条款才能理解为什么这样可以:
If
x
has typeX
andy
has typeY
then
If an implicit conversion (§6.1) exists from
X
toY
, but not fromY
toX
, thenY
is the type of the conditional expression.If an implicit conversion (§6.1) exists from
Y
toX
, but not fromX
toY
, thenX
is the type of the conditional expression.Otherwise, no expression type can be determined, and a compile-time error occurs.
这里的x
是int
类型,y
是int?
类型。没有从 int?
到 int
的隐式转换,但是有从 int
到 int?
的隐式转换所以表达式的类型是 int?
。
1:进一步注意,在确定条件表达式的类型时忽略了左侧的类型,这是此处常见的混淆来源。
关于c# - 无法确定条件表达式的类型,因为 'int' 和 <null> 之间没有隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260528/
我是一名优秀的程序员,十分优秀!