ตัวดำเนินการ "as" ทำการแปลงระหว่างประเภทที่เข้ากันได้ มันเหมือนกับการดำเนินการแคสต์และมันทำเฉพาะการแปลงอ้างอิง การแปลงที่ไม่มีค่า และการแปลงการชกมวย ตัวดำเนินการ as ไม่สามารถทำการแปลงอื่นๆ เช่น การแปลงที่ผู้ใช้กำหนด ซึ่งควรดำเนินการโดยใช้นิพจน์การแคสต์แทน
ต่อไปนี้คือตัวอย่างที่แสดงการใช้งาน as operation ใน C# 'as' ใช้สำหรับการแปลง:
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!