C# 中的逻辑运算符有哪些?
csharpprogrammingserver side programming更新于 2025/10/15 18:52:17
逻辑运算符用于布尔值。C# 中有以下三个逻辑运算符。
| 运算符 | 描述 |
|---|---|
| && | 称为逻辑"与"运算符。如果两个操作数都非零,则条件成立。 |
| || | 称为逻辑"或"运算符。如果两个操作数中有一个非零,则条件成立。 |
| ! | 称为逻辑"非"运算符。用于反转其操作数的逻辑状态。如果条件为真,则逻辑非运算符将返回假。 |
让我们看一个示例,展示如何在 C# 中使用逻辑运算符。这里检查条件是否为逻辑与运算符。
if (a && b) {
Console.WriteLine("Line 1 - 条件为真");
}
同样,让我们看看如何在 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

