Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้งาน as Operator ใน C#

ออเปอเรเตอร์ as ทำการแปลงชนิดระหว่างชนิดที่เข้ากันได้ (compatible types) คล้าย cast operation แต่ทำได้เฉพาะ reference conversions, nullable conversions, และ boxing conversions ไม่สามารถทำ user-defined conversions ได้

ตัวอย่าง

string s = obj[i] as string;

ตัวอย่างเต็ม

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!