可空类型和三元运算符:为什么是`?10 : null` 被禁止? [英] Nullable types and the ternary operator: why is `? 10 : null` forbidden?

查看:20
本文介绍了可空类型和三元运算符:为什么是`?10 : null` 被禁止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到一个奇怪的错误:

I just came across a weird error:

private bool GetBoolValue()
{
    //Do some logic and return true or false
}

然后,在另一种方法中,像这样:

Then, in another method, something like this:

int? x = GetBoolValue() ? 10 : null;

简单,如果方法返回true,则将10赋给Nullableint x.否则,将 null 分配给 nullable int.然而,编译器抱怨:

Simple, if the method returns true, assign 10 to the Nullableint x. Otherwise, assign null to the nullable int. However, the compiler complains:

错误 1 ​​无法确定条件表达式的类型,因为 int 之间没有隐式转换.

Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between int and <null>.

我要疯了吗?

推荐答案

编译器首先尝试计算右手表达式:

The compiler first tries to evaluate the right-hand expression:

GetBoolValue() ? 10 : null

10int 文字(不是 int?),null>null.这两者之间没有隐式转换,因此出现错误消息.

The 10 is an int literal (not int?) and null is, well, null. There's no implicit conversion between those two hence the error message.

如果将右侧表达式更改为以下表达式之一,则它会编译,因为 int?null (#1) 之间以及之间存在隐式转换intint? (#2, #3).

If you change the right-hand expression to one of the following then it compiles because there is an implicit conversion between int? and null (#1) and between int and int? (#2, #3).

GetBoolValue() ? (int?)10 : null    // #1
GetBoolValue() ? 10 : (int?)null    // #2
GetBoolValue() ? 10 : default(int?) // #3

这篇关于可空类型和三元运算符:为什么是`?10 : null` 被禁止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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