为什么这两个表达式在语义上不相同?

Fra*_*zzi 2 c#

为什么第一个测试会引发编译器错误而第二个测试没有?对我来说,他们似乎在语义上等同.

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)

kni*_*ttl 9

条件运算符要求两个操作数具有相同的类型.null并且bool不兼容,并且没有自动转换boolnull.你需要明确地演员:

return input ? (bool?)input : null;
Run Code Online (Sandbox Code Playgroud)

在另一方面,没有从自动转换boolbool?,也来自nullbool?,这就是为什么你可以返回bool,并null从一个bool?方法.