为什么我不能设置一个可空INT为NULL if语句三元? [英] Why can't I set a nullable int to null in a ternary if statement?

查看:97
本文介绍了为什么我不能设置一个可空INT为NULL if语句三元?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#code如下:

int? i;
i = (true ? null : 0);

给我的错误:

有条件的前pression的类型不能
  来确定,因为没有
  之间的隐式转换'<&空GT;'
  和INT

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

应该不是这个有效吗?我在这里丢失怎么办?

Shouldn't this be valid? What am i missing here?

推荐答案

编译器尝试计算右手前pression。 0 INT 的文字,而不是 INT?。编译器是想告诉你,它不能确定是什么类型的前任pression应评估作为。有之间没有隐式转换 INT ,因此错误消息。

The compiler tries to evaluate the right-hand expression. null is null and the 0 is an int literal, not int?. The compiler is trying to tell you that it can't determine what type the expression should evaluate as. There's no implicit conversion between null and int, hence the error message.

您需要告诉恩pression应该评估为 INT?的编译器。有 INT? INT 之间,或 INT ,所以无论这些应该工作:

You need to tell the compiler that the expression should evaluate as an int?. There is an implicit conversion between int? and int, or between null and int?, so either of these should work:

int? x = true ? (int?)null : 0;

int? y = true ? null : (int?)0;

这篇关于为什么我不能设置一个可空INT为NULL if语句三元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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