【发布时间】:2020-02-12 14:27:03
【问题描述】:
在否定bool? 的null 值的情况下,我对c# 编译器感到困惑。编译器将!null 解释为null。我的期望是提高
CS0266(无法将类型“bool?”隐式转换为“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
有人可以证明为什么编译器是正确的,反之亦然。
【问题讨论】:
-
this answer 有帮助吗? - “Nullable
是一种非常特殊的类型,它的神奇属性深深嵌入在 C# 语言和运行时” -
@stuartd 来自 canton7 的答案似乎更短更清晰。
标签: c# compiler-errors logical-operators