简体   繁体   English

为什么这个C#代码没有编译?

[英]Why doesn't this C# code compile?

double? test = true ? null : 1.0;

In my book, this is the same as 在我的书中,这是一样的

if (true) {
  test = null;
} else {
  test = 1.0;
}

But the first line gives this compiler error: 但是第一行给出了这个编译错误:

Type of conditional expression cannot be determined because there is no implicit conversion between ' <null> ' and ' double '. 无法确定条件表达式的类型,因为' <null> '和' double '之间没有隐式转换。

This happens because the compiler tries to evaluate the statement from right to left. 发生这种情况是因为编译器尝试从右到左计算语句。 This means that it sees 1.0 and it decides it is double (not double?) and then it sees null . 这意味着它看到1.0并且它决定它是double(不是double?)然后它看到null

So there is clearly no implicit conversion between double and null (in fact there is no implicit conversion between Struct and null ). 因此, doublenull之间显然没有隐式转换(事实上, Structnull之间没有隐式转换)。

What you can do is explicitly tell the compiler that one of the two expressions that are convertible to each other. 你可以做的是明确告诉编译器两个表达式中的一个可以相互转换。

double? test = true ? null : (double?) 1.0;    // 1
double? test = true ? (double?)null : 1.0;     // 2
double? test = true ?  default(double?) : 1.0; // 3
double? test = true ? new double?() : 1.0;     // 4
double? test = true ? (double?)null : 1.0;

will work. 将工作。 That's because there is no conversion from the type of the first expression ( null ) to the type of the second expression ( double ). 那是因为没有从第一个表达式( null )的类型到第二个表达式( double )的类型的转换。

The left hand side of the assignment is not used when deducing the type of an ?: expression. 在推导出?:表达式的类型时,不使用赋值的左侧。

In b ? A : B b ? A : B b ? A : B , the types of A and B must either be the same, or one must be implicitly convertible to the other. b ? A : BAB的类型必须相同,或者必须可以隐式转换为另一个。

Because the compiler can't figure out that for null and 1.0 to be compatible, the values need to be cast to double?. 因为编译器无法弄清楚null和1.0是否兼容,所以需要将值转换为double?。 This needs to be explicitly stated. 这需要明确说明。

double? test = true ? (double?) null : 1.0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM