为什么第一个测试会引发编译器错误而第二个测试没有?对我来说,他们似乎在语义上等同.
public bool? inlineTest(bool input)
{
return input ? null : input;
}
public bool? expandedTest(bool input)
{
if (input)
return input;
else
return null;
}
Run Code Online (Sandbox Code Playgroud)
条件运算符要求两个操作数具有相同的类型.null并且bool不兼容,并且没有自动转换bool为null.你需要明确地演员:
return input ? (bool?)input : null;
Run Code Online (Sandbox Code Playgroud)
在另一方面,没有从自动转换bool到bool?,也来自null于bool?,这就是为什么你可以返回bool,并null从一个bool?方法.