3

有人可以解释一下我必须投到的逻辑原因吗nullint?

什么时候左参数类型可以同时具有它们的两种类型?

决定做

  int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : null);

我必须这样做

  int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);

虽然int? k = null是完全有效的。

一个相反的例子:

我不必这样做:

string k = (DateTime.Now.Ticks%5 > 3 ? "lala" : null);

4

2 回答 2

10
int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);

在这种情况下,我们所拥有的是 1int并且null实际上是null 现在混淆是三元运算符被混淆为什么是返回类型int或以及null因为int它不会接受null

因此,您需要将其转换为可为空的int

现在在另一种情况下,您有一个字符串,并且 null 完全可以接受string

进一步的解释可以在类型推断中找到 - Eric

?: 运算符的第二个和第三个操作数控制条件表达式的类型。设 X 和 Y 是第二个和第三个操作数的类型。然后,

  • 如果 X 和 Y 是相同的类型,那么这是条件表达式的类型。

  • 否则,如果存在从 X 到 Y 的隐式转换,但不存在从 Y 到 X 的转换,则 Y 是条件表达式的类型。

  • 否则,如果存在从 Y 到 X 的隐式转换,但不存在从 X 到 Y 的转换,则 X 是条件表达式的类型。

  • 否则,无法确定表达式类型,并出现编译时错误。

于 2013-02-07T08:08:40.987 回答
2

因为编译器不使用左侧变量的类型来确定右侧表达式的类型。首先它确定表达式的类型,然后确定是否可以将其放入变量中。

There is no type close enough that is common between an int and a null value. You have to either make the int value nullable or the null value "intable" for the compiler to find a common ground for the values.

When you have a string and a null value the compiler can simply use one of the types, because a string is already nullable.

于 2013-02-07T08:14:56.470 回答