【问题标题】:Why aren't those two expressions semantically equivalent?为什么这两个表达式在语义上不等价?
【发布时间】:2016-04-27 09:33:37
【问题描述】:

为什么第一个测试会引发编译器错误,而第二个不会?在我看来,它们在语义上是等价的。

public bool? inlineTest(bool input)
{
    return input ? null : input;
}

public bool? expandedTest(bool input)
{
    if (input)
        return input;
    else
        return null;
}

【问题讨论】:

    标签: c#


    【解决方案1】:

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

    return input ? (bool?)input : null;
    

    另一方面,从boolbool? 以及从nullbool? 的自动转换,这就是为什么您可以从bool? 返回boolnull方法。

    【讨论】:

    • expandedTest 的等价物不是return input ? (bool?)input : null; 吗?
    • @Fermin:你是对的,条件中的逻辑是相反的。我从 OP 复制粘贴了代码。现已修复。
    【解决方案2】:

    类型推断规则规定:

    first_expression 和 second_expression 的类型必须是 相同,或者必须存在从一种类型到另一种类型的隐式转换。

    所以编译器能够推断出bool?的类型。

    这种类型推断不会发生在 if 语句中,因此您的工作是明确声明类型。

    【讨论】:

      【解决方案3】:

      使用条件运算符时,两个操作数应具有相同的数据类型。

      【讨论】:

        猜你喜欢
        • 2018-01-21
        • 1970-01-01
        • 2016-09-12
        • 1970-01-01
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 1970-01-01
        • 2021-05-08
        相关资源
        最近更新 更多