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

typeof, GetType, is trong C#

typeof()

Toán tử typeof lấy Type và trả về Type của argument (compile-time).

GetType()

Phương thức GetType() của class Array (và object) lấy Type của current instance (runtime).

is

Từ khóa "is" kiểm tra object có thể cast sang kiểu cụ thể không. Kết quả trả về Boolean.

Ví dụ

class Demo { }

class Program
{
    static void Main()
    {
        var demo = new Demo();
        Console.WriteLine($"typeof: {typeof(Demo)}");
        Type tp = demo.GetType();
        Console.WriteLine($"GetType: {tp}");
        if (demo is Demo)
        {
            Console.WriteLine("is keyword check: true");
        }
        Console.ReadLine();
    }
}

Kết quả

typeof: ConsoleApp.Demo
GetType: ConsoleApp.Demo
is keyword check: true