Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Mục đích của toán tử 'as' trong C#

Toán tử "as" thực hiện chuyển đổi giữa các kiểu tương thích. Giống cast nhưng chỉ làm reference conversions, nullable conversions, boxing conversions. Không làm user-defined conversions (cần cast expressions).

Ví dụ dùng as để chuyển đổi:

string s = obj[i] as string;

Ví dụ

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();
    }
}

Kết quả

0: 'jack' 1: This is not a string!