Logical operators
ตัวดำเนินการเชิงตรรกะ (logical operators) มักจะใช้ในการตรวจสอบกับค่าของ boolean โดยปกติตัวดำเนินการเปรียบเทียบจะให้ผลลัพธ์เป็น boolean อยู่แล้ว ในภาษา C# มีตัวดำเนินการเชิงตรรกะอยู่ 3 แบบ
ตารางของ logical operators
Symbol |
Name |
Example |
! |
Not |
! (n==1) |
&& |
And |
a == 1 && b == 1 |
|| |
Or |
a == 1 || b == 1 |
ตัวอย่างการใช้ตัวดำเนินการเชิงตรรกะ
using System;
class LogicalOperators
{
static void Main(string[] args)
{
bool a = (3 == 4);
bool b = (3 != 4);
bool c = (3 < 4);
bool d = a && c;
bool e = !d;
Console.WriteLine(“a = ” + a);
Console.WriteLine(“b = ” + b);
Console.WriteLine(“c = ” + c);
Console.WriteLine(“d = ” + d);
Console.WriteLine(“e = ” + e);
}
}
จากตัวอย่างด้านบน ได้มีการสร้างตัวแปร boolean สำหรับเก็บค่าจาก expression ที่ถูกประเมินผลกับโอเปอแรน ตัวดำเนินการเปรียบเทียบและตัวดำเนินการตรรกะ ที่มันจะ return ค่าสุดท้ายคือ True หรือ False
a = False
b = True
c = True
d = False
e = True
ผลลัพธ์ของโปรแกรม
ตัวดำเนินการตรรกะโดยปกติมักจะใช้กับคำสั่งเงื่อนไขหรือคำสั่งวนซ้ำ ดังตัวอย่างข้างล่างนี้
using System;
class LogicalOperators
{
static void Main(string[] args)
{
int age = 20;
int money = 100;
if(age >= 18 && money >= 120) {
Console.WriteLine(“You can buy a game.”);
}
if(age >= 18 || money >= 500) {
Console.WriteLine(“You can buy a movie.”);
}
}
}
ตัวอย่าง ได้มีการสร้างเงื่อนไขเพิ่มเติมโดยการใช้ตัวดำเนินการตรรกะ เราใช้ตัวดำเนินการ “and” && นั่นหมายความว่าแต่ละ expression ย่อยต้องมีค่าเป็นจริง สำหรับการซื้อเกมผู้ใช้ต้องมีอายุตั้งแต่ 18 ปีขึ้นไปและต้องมีเงินตั้งแต่ 120 ขึ้นไป สำหรับการซื้อภาพยนตร์ เราได้ใช้ตัวดำเนินการ “or” || โดยเราต้องการเพียงแค่เงื่อนไขใดเงื่อนไขหนึ่งเท่านั้นที่เป็นจริง หรือทั้งสอง