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

查看:726
本文介绍了可空类型和三元运算符:为什么`? 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可空 INT X。否则,分配null以在可为空 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类型条件前pression的,因为有 INT 之间不存在隐式转换和<零>

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

我要去疯了吗?

推荐答案

编译器第一次尝试计算右手前pression:

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

GetBoolValue() ? 10 : null

10 INT 文字(不 INT?)和是,好了,。有这两个因而错误信息之间不存在隐式转换。

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.

如果你改变了右手前pression到那么下面的一个可以编译因为 INT?和<$ C $之间的隐式转换C>无效(#1)之间的 INT INT?(#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天全站免登陆