ตัวดำเนินการ IS
โอเปอเรเตอร์ "is" ใน C# จะตรวจสอบว่าประเภทรันไทม์ของออบเจ็กต์เข้ากันได้กับประเภทที่กำหนดหรือไม่
ต่อไปนี้เป็นวากยสัมพันธ์ −
expr is type
ที่นี่ ด่วน คือนิพจน์
ประเภท เป็นชื่อประเภท
ต่อไปนี้คือตัวอย่างการแสดงการใช้ isoperator ใน C# &minis;
ตัวอย่าง
using System;
class One { }
class Two { }
public class Demo {
public static void Test(object obj) {
One x;
Two y;
if (obj is One) {
Console.WriteLine("Class One");
x = (One)obj;
} else if (obj is Two) {
Console.WriteLine("Class Two");
y = (Two)obj;
} else {
Console.WriteLine("None of the classes!");
}
}
public static void Main() {
One o1 = new One();
Two t1 = new Two();
Test(o1);
Test(t1);
Test("str");
Console.ReadKey();
}
} ผลลัพธ์
Class One Class Two None of the classes!
ตัวดำเนินการ AS
ตัวดำเนินการ "as" ทำการแปลงระหว่างประเภทที่เข้ากันได้ มันเหมือนกับการดำเนินการแคสต์และมันทำเฉพาะการแปลงอ้างอิง การแปลงที่ไม่มีค่า และการแปลงการชกมวย ตัวดำเนินการ as ไม่สามารถทำการแปลงอื่นๆ เช่น การแปลงที่ผู้ใช้กำหนด ซึ่งควรดำเนินการโดยใช้นิพจน์การแคสต์แทน
ต่อไปนี้คือตัวอย่างที่แสดงการใช้งาน as operation ใน C# ตามที่ใช้สำหรับการแปลง -
string s = obj[i] as string;
ลองเรียกใช้รหัสต่อไปนี้เพื่อทำงานกับตัวดำเนินการ 'as' ใน C# -
ตัวอย่าง
using System;
public class Demo {
public static void Main() {
object[] obj = new object[2];
obj[0] = "jack";
obj[1] = 32;
for (int i = 0; i < obj.Length; ++i) {
string s = obj[i] as string;
Console.Write("{0}: ", i);
if (s != null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("This is not a string!");
}
Console.ReadKey();
}
} ผลลัพธ์
0: 'jack' 1: This is not a string!