c# - Nullable <bool>的null否定

标签 c# compiler-errors logical-operators

在否定nullbool?值的情况下,我对C#编译器感到困惑。编译器会将!null解释为null。我的期望是提高

CS0266 (Cannot implicitly convert type 'bool?' to 'bool')



样例代码:
bool? nullableVal = null;

//if (nullableVal)  //OK: CS0266 bool? can't be converted to bool
//    ;
var expectCS0266 = !nullableVal;//No compiler error/warning

//if ((!null) ?? false)//OK: CS8310 Operator '!' cannot be applied to operands of type "<NULL>"
//    ;

if (! nullableVal ?? false)
    ;//this statement isn't reached, because of precedence of ! is higher than ??
    //and !null == null

if (!(nullableVal ?? false))
    ;//this statement is reached, OK

有人可以证明为什么编译器是正确的,反之亦然。

最佳答案

参见the spec的7.3.7节:

Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. Lifted operators are constructed from predefined and user-defined operators that meet certain requirements, as described in the following:

  • For the unary operators
        + ++ - -- ! ~
    a lifted form of an operator exists if the operand and result types are both non-nullable value types. The lifted form is constructed by adding a single ? modifier to the operand and result types. The lifted operator produces a null value if the operand is null. Otherwise, the lifted operator unwraps the operand, applies the underlying operator, and wraps the result.


(强调我的)

所以:
bool? x = null;
bool? y = !x;

遵守此规则。我们使用的是一元!运算符的提升形式,如果应用于的值是null,则将生成null

禁止使用!null,因为null的类型不是Nullable<T>!(bool?)null有效(尽管它会产生编译器警告)。
!确实比??具有更高的优先级,请参阅第7.3.1节。

关于c# - Nullable <bool>的null否定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60190565/

相关文章:

java - 如何对 java.util.Arrays.toString 使用静态导入?

android - Admob尚未运行时,将其添加到我现有的项目中

java 使用逻辑运算符代替 if-else if 进行返回

javascript - NOT 与 NULL 与本地存储

C# 和 SQLite : "no such table error" when using relative path?

c# - System.Speech.Synthesis 在 2012 R2 上因高 CPU 而挂起

c# - 在关系数据库中保存任何类型的对象

c# - 托管 WCF 服务的各种方法有哪些?

c++ - 如何将单个对象转换为boost::any_range?

javascript - 逻辑运算符和if语句组合