目录

Show 例子

下表显示了C#支持的所有逻辑运算符。 假设变量A保持布尔值true,变量B保持布尔值false,则 -

操作者 描述
&& 称为逻辑AND运算符。 如果两个操作数都不为零,则条件成立。 (A && B)是假的。
|| 称为逻辑OR运算符。 如果两个操作数中的任何一个不为零,则条件变为真。 (A || B)是真的。
! 称为逻辑非运算符。 用于反转其操作数的逻辑状态。 如果条件为真,则Logical NOT运算符将为false。 !(A && B)是真的。

例子 (Example)

以下示例演示了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
↑回到顶部↑
WIKI教程 @2018