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

วิธีใช้เมธอด GetType() ของคลาส Array ใน C#


เมธอด GetType() ของคลาส Array ใน C# ดึงประเภท (Type) ของอินสแตนซ์ปัจจุบัน (สืบทอดมาจาก Object)

เพื่อดึงประเภท

Type tp = value.GetType();

ในตัวอย่างด้านล่าง เราตรวจสอบค่า int ด้วย Type

if (tp.Equals(typeof(int))) 
    Console.WriteLine("{0} is an integer data type.", value)

การใช้งาน GetType() ใน C#

ตัวอย่าง

using System; 
public 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); 
        } 
    } 
}