C#中的逻辑运算符是什么?

逻辑运算符与布尔值一起使用。以下三个逻辑运算符在C#中可用。

运算符描述
&&称为逻辑AND运算符。如果两个操作数都不为零,则条件为真。
||称为逻辑或运算符。如果两个操作数中的任何一个都不为零,则条件为真。
称为逻辑非运算符。用于反转其操作数的逻辑状态。如果条件为真,则逻辑非运算符将为假。

让我们看一个示例,该示例显示如何在C#中使用逻辑运算符。在此检查逻辑AND运算符的条件。

if (a && b) {

   Console.WriteLine("Line 1 - Condition is true");

}

同样,让我们看看如何与C#中的其他逻辑运算符一起使用。

示例

using System;

namespace Demo {

   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");

         }

         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

以上是 C#中的逻辑运算符是什么? 的全部内容, 来源链接: utcz.com/z/355591.html

回到顶部