gpt4 book ai didi

c# - 无法确定条件表达式的类型,因为 'int' 和 之间没有隐式转换

转载 作者:IT王子 更新时间:2023-10-29 03:32:41 25 4
gpt4 key购买 nike

为什么不能编译?

int? number = true ? 5 : null;

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

最佳答案

规范 (§7.14) 说对于条件表达式 b ? x : y,存在三种可能性,xy 都具有类型某些良好条件 满足,xy 中只有一个具有类型并且满足某些良好条件,或发生编译时错误。这里的“一定的好条件”是指一定的转换是可能的,我们将在下面详细介绍。

现在,让我们转向规范的相关部分:

If only one of x and y has a type, and both x and y are implicitly convertible to that type, then that is the type of the conditional expression.

这里的问题是

int? number = true ? 5 : null;

只有一个条件结果有类型。这里 x 是一个 int 字面量,而 ynull null 类型不能隐式转换为 int1。因此,不满足“某些良好条件”,就会出现编译时错误。

两种解决方法:

int? number = true ? (int?)5 : null;

这里我们仍然处于只有 xy 之一有类型的情况。请注意,null 仍然 没有类型,但编译器对此不会有任何问题,因为 (int?)5null 都可以隐式转换为 int?(§6.1.4 和 §6.1.5)。

另一种方式显然是:

int? number = true ? 5 : (int?)null;

但现在我们必须阅读规范中的一个不同条款才能理解为什么这样可以:

If x has type X and y has type Y then

  • 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.

  • 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.

这里的xint类型,yint?类型。没有从 int?int 的隐式转换,但是有从 intint? 的隐式转换所以表达式的类型是 int?

1:进一步注意,在确定条件表达式的类型时忽略了左侧的类型,这是此处常见的混淆来源。

关于c# - 无法确定条件表达式的类型,因为 'int' 和 <null> 之间没有隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com