可空布尔逻辑“ AND”运算符在正确和错误

时间:2019-01-07 12:00:03

标签: c# nullable logical-operators

使用bool?变量,有人可以解释为什么true & null产生nullfalse & null产生false的原因吗?

void Main()
{    
    bool? a = null;
    bool? b = true;
    bool? c = a & b;

    Console.WriteLine($"{b} & NULL => " + c);

    b = false;
    c = a & b;
    Console.WriteLine($"{b} & NULL => " + c);
}

输出:

  

True&NULL =>
  False&NULL => False

我也很高兴看到重复的照片,因为我还没有找到它。

4 个答案:

答案 0 :(得分:1)

在这种情况下(a&b),编译器仅在找到1 false时返回false,否则对a和b进行比较,则在这种情况下无法返回实际结果,则什么也不返回!

答案 1 :(得分:1)

使用可为空的类型意味着您的布尔值实际上可以具有3个值,truefalsenull。这意味着您必须以three-valued logic来表示。

This answer(用于sql问题)涵盖了使用三值逻辑时ANDOR的结果。

答案 2 :(得分:1)

答案是笨蛋?类型已设计为与SQL布尔值匹配,如此处所述 Using nullable types (C# Programming Guide) 并在下面引用

  

布尔?输入

     

布尔?可为空的类型可以包含三个不同的值:true,   false和null。笨蛋?类型就像布尔变量类型   在SQL中使用。确保由&和|产生的结果   运算符与SQL中的三值布尔类型一致,   提供了以下预定义的运算符:•布尔?算子   &(bool?x,bool?y)•bool?运算符|(bool?x,bool?y)

     

这些运算符的语义由下表定义:

     

x y x&y x | y

     

true true true true
  真假假真
  true null null tr​​ue
  假真假真
  假假假
  假null假null
  null tr​​ue null tr​​ue
  null假false null
  null null null null

     

请注意,这两个运算符不遵循   运算符部分:运算符评估的结果可以是   即使操作数之一为null也不为null。

答案 3 :(得分:1)

The purpose of null in this is case is to identity an unknown value. In three-valued logic, the purpose of the unknown value is to indicate that we do not know anything about the truthy or the falsy of a predicated.

false AND unknown returns false because it is not important to know what the second operator is. This is due to the and operator nature that requires both the operands to be true to return true. As we know that the first operand is false, the rest is irrelevant, and the result is false.

On the other hand, true AND unknown returns unknown, because the first operand is true, and therefore the result of the whole operation depends on the second operand. The second operand is unknown, therefore the result is unknown.

C# indicates unknown with null.