ตัวดำเนินการเชิงตรรกะใช้กับค่าบูลีน ตัวดำเนินการเชิงตรรกะสามตัวต่อไปนี้มีอยู่ใน C#
| ตัวดำเนินการ | คำอธิบาย |
|---|---|
| && | เรียกว่าตัวดำเนินการตรรกะ AND ถ้าตัวถูกดำเนินการทั้งสองไม่ใช่ศูนย์ เงื่อนไขจะกลายเป็นจริง |
| || | เรียกว่าตรรกะหรือตัวดำเนินการ ถ้าตัวถูกดำเนินการสองตัวใดตัวหนึ่งไม่เป็นศูนย์ เงื่อนไขจะกลายเป็นจริง |
| ! | เรียกว่าตรรกะไม่ใช่ตัวดำเนินการ ใช้เพื่อย้อนกลับสถานะตรรกะของตัวถูกดำเนินการ หากเงื่อนไขเป็นจริง ตัวดำเนินการ Logical NOT จะทำให้เป็นเท็จ |
ให้เรามาดูตัวอย่างที่แสดงวิธีการทำงานกับตัวดำเนินการเชิงตรรกะใน C# มีการตรวจสอบเงื่อนไขสำหรับตัวดำเนินการ Logical 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