为什么第一个测试会引发编译器错误,而第二个测试不会呢?对我来说,他们似乎语义上相同。为什么这两个表达式在语义上不相等?
public bool? inlineTest(bool input)
{
return input ? null : input;
}
public bool? expandedTest(bool input)
{
if (input)
return input;
else
return null;
}
为什么第一个测试会引发编译器错误,而第二个测试不会呢?对我来说,他们似乎语义上相同。为什么这两个表达式在语义上不相等?
public bool? inlineTest(bool input)
{
return input ? null : input;
}
public bool? expandedTest(bool input)
{
if (input)
return input;
else
return null;
}
条件运算符要求两个操作数都是相同的类型。 null
和bool
不兼容,并且没有自动从bool
到null
的转换。你需要明确地投:
return input ? (bool?)input : null;
在另一方面,有一个自动转换从bool
到bool?
,也从null
到bool?
,这就是为什么你可以从bool?
方法返回一个bool
和null
。
类型推理规则规定:
要么first_expression和second_expression的类型必须是 相同,或隐式转换必须存在从一种类型到另一个。
所以编译器能够推断出类型,如bool?
。
此类型推断不会发生在if
语句中,因此您的工作是明确说明类型。
两个操作数在使用条件运算符时应该具有相同的数据类型。
ExpandedTest的等价物是不是'返回输入? (bool?)input:null;'? – Fermin
@Fermin:你说得对,条件中的逻辑是倒置的。我复制了来自OP的代码。现在修复。 – knittl