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

Typeof() vs GetType() ใน C#

Typeof()

รับ Type แล้วคืน Type ของ Argument

typeof(byte) // คืน System.Byte

ตัวอย่าง

using System;
class Program {
    static void Main() {
        Console.WriteLine(typeof(int));
        Console.WriteLine(typeof(byte));
    }
}

ผลลัพธ์

System.Int32
System.Byte

GetType()

เมธอดของ Object คืน Type ของ Instance ปัจจุบัน

Type tp = value.GetType();

ตัวอย่าง

using System;
class Program {
    public static void Main() {
        object[] values = { (int)100, (long)17111 };
        foreach (var value in values) {
            Type tp = value.GetType();
            if (tp.Equals(typeof(int)))
                Console.WriteLine("{0} is an integer data type.", value);
            else
                Console.WriteLine("'{0}' is not an int data type.", value);
        }
    }
}

ผลลัพธ์

100 is an integer data type.
'17111' is not an int data type.