【问题标题】:How to determine the result of a logical operator on nullable booleans?如何确定可空布尔值的逻辑运算符的结果?
【发布时间】:2010-11-25 20:06:42
【问题描述】:

例如,在 C# 中,当我比较两个可为空的布尔值 (bool?) 时,我得到以下结果:

true & null = null
false & null = false
true | null = true
false | null = null

问题是我无法理解这些结果是如何产生的,当其中一个为空时,我可以使用什么规则来确定逻辑运算符对两个布尔值的结果?

【问题讨论】:

    标签: c# .net operators boolean


    【解决方案1】:

    这里的想法是“null”意味着“未知”,或者“信息不足”。因此,如果答案取决于未知值,则答案本身是未知的。如果无论未知值是什么(例如true | null)答案都相同,那么您仍然可以。

    这样想:

    y = true & x; // the result will be the same as the value of x (it depends on x)
    y = true | x; // the result will be true whatever x is
    

    【讨论】:

    • 我认为您在第一条评论中的意思是 it has to be x 而不是 it has to be true,即 y 将是 x 将是什么。
    • @GDS:嗯,我的意思是“x 必须为真,y 才能为真”,但为了清楚起见,我会进行编辑。
    猜你喜欢
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多