本文介绍了为什么 null 需要显式类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码无法编译:
//int a = ...
int? b = (int?) (a != 0 ? a : null);
为了编译,需要改成
int? b = (a != 0 ? a : (int?) null);
因为 b = null
和 b = a
都是合法的,这对我来说没有意义.
Since both b = null
and b = a
are legal, this doesn't make sense to me.
为什么我们必须将 null
转换为 int?
并且为什么我们不能简单地为整个表达式提供显式类型转换(我知道是在其他情况下可能)?
Why do we have to cast the null
into an int?
and why can't we simply provide an explicit type cast for the whole expression (which I know is possible in other cases)?
推荐答案
来自 C# 语言规范的第 7.13 章:
From chapter 7.13 of the C# Language Specification:
?: 运算符的第二个和第三个操作数控制条件表达式的类型.设 X 和 Y 是第二个和第三个操作数的类型.那么,
- 如果 X 和 Y 的类型相同,则这是条件表达式的类型.
- 否则,如果存在从 X 到 Y 的隐式转换(第 6.1 节),但不存在从 Y 到 X 的隐式转换,则 Y 是条件表达式的类型.
- 否则,如果存在从 Y 到 X 的隐式转换(第 6.1 节),但不存在从 X 到 Y 的隐式转换,则 X 是条件表达式的类型.
- 否则,无法确定表达式类型,并发生编译时错误.
在您的情况下,没有从 int 到 null 的隐式转换,反之亦然.你的演员解决了这个问题,int 可以转换为 int?
In your case, there is no implicit conversion from int to null nor the other way around. Your cast solves the problem, int is convertible to int?
这篇关于为什么 null 需要显式类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!