为什么空需要在这里投下了明确的类型? [英] Why does null need an explicit type cast here?

查看:208
本文介绍了为什么空需要在这里投下了明确的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code不能编译:

The following code does not compile:

//int a = ...
int? b = (int?) (a != 0 ? a : null);

为了进行编译,它需要被改变成

In order to compile, it needs to be changed to

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.

为什么我们要投诠释?,为什么我们不能简单地提供一个显式类型转换为整个前pression(我知道有可能在其他情况下)?

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:

的第二个和第三个操作数:操作员控制的条件EX pression类型。设X和Y是在第二和第三操作数的类型。然后,

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

      
  • 如果X和Y是相同的类型,那么这是的有条件前pression类型。
  •   
  • 否则,如果隐式转换(第6.1节)存在从X到Y,但不能从Y到X,然后Y是的有条件前pression类型。
  •   
  • 否则,如果隐式转换(第6.1节)存在从Y到X,但不能从X到Y,则X是的有条件前pression类型。
  •   
  • 否则,没有EX pression类型可确定,并发生编译时错误。
  •   
  • If X and Y are the same type, then this is the type of the conditional expression.
  • Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
  • Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
  • Otherwise, no expression type can be determined, and a compile-time error occurs.

在你的情况,没有从int隐式转换为空,也没有其他方式。你投解决问题,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?

这篇关于为什么空需要在这里投下了明确的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆