下表列出了所有C#所支持的逻辑运算符。假设变量A持有布尔值true和变量B持有布尔值false,那么:
运算符 | 描述 | 示例 |
---|---|---|
&& | 所谓逻辑与操作。如果两个操作数为非零则条件为真 | (A && B) 结果为 false. |
|| | 所谓逻辑或操作。如果任何两个操作数是非零则条件变为真 | (A || B) 结果为 true. |
! | 所谓逻辑非运算符。使用反转操作数的逻辑状态。如果条件为真,那么逻辑非操作符结果为假(false) | !(A && B) 结果为 true. |
例子
试试下面的例子就明白了所有的在C#中可用的逻辑运算符:
using System; namespace OperatorsAppl { class Program { static void Main(string[] args) { bool a = true; bool b = true; if (a && b) { Console.WriteLine("Line 1 - Condition is true"); } if (a || b) { Console.WriteLine("Line 2 - Condition is true"); } /* lets change the value of a and b */ a = false; b = true; if (a && b) { Console.WriteLine("Line 3 - Condition is true"); } else { Console.WriteLine("Line 3 - Condition is not true"); } if (!(a && b)) { Console.WriteLine("Line 4 - Condition is true"); } Console.ReadLine(); } } }
让我们编译和运行上面的程序,这将产生以下结果:
Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is not true Line 4 - Condition is true