【发布时间】:2011-05-22 22:51:26
【问题描述】:
可能重复:
AND operation cannot be applied between nullable bools.
我希望有类似的行为,例如 + 或 *。因此,如果任何操作数为 null,它应该返回 null,但如果在 && 或 || 中使用,编译会报错。为什么?
为了说明这一点:
//this compiles
int? x = null;
int? y = null;
var z = x*y;
// this doesn't compile
bool? x = null;
bool? y = null;
if(x && y)
....
【问题讨论】:
-
你能提供一些失败的示例代码吗?我不确定我是否理解您所指的内容。
-
"如果任何操作数为 null,则应返回 null":
&&和||运算符属于 bool 类型,因此将始终返回布尔结果。当您获得可空类型时,只需使用myNullable.HasValue && ... -
AND operation cannot be applied between nullable bools. 的可能副本,请参阅 Eric Lippert 的 excellent answer and the examples he provides
-
抱歉重复。我现在明白了为什么它在本质上不受支持,尽管在某些情况下它可能是有道理的。