C# 中的布尔赋值运算符

Boolean Assignment Operators in C#

这个 ^= 布尔赋值运算符在 C# 中是如何工作的,^ 运算符的数学名称是什么?它与 &| 运算符有何不同?

Docs:

Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.

在数学上,这叫做互斥

开发人员用例:

您可能有某个 UI 需要同时输入 2 个字段(但均为空也有效)。在这种情况下,您可以使用 XOR 运算符来检查一个字段是否已填写而另一个字段是否未填写。

^&| 的区别:

  • 真 & 假 => 假;
  • 真 |假 => 真;
  • 真 ^ 假 => 真;

  • true ^ true => false 而 true & true => true 和 true | true => true

规则:

  • &:两者都应为真才能产生真。
  • |:至少有一个为真才能产生真。
  • ^:只有一个操作数应该为真才能产生真。

使用 b1 ^= b2; 等同于 b1 = b1 ^ b2;,因此上述规则适用。

^ 表示一个操作数应该为真或假,这将 return 假,因为 true/false