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

การได้ประเภทของอินสแตนซ์ปัจจุบันใน C#

ใน C# ทุกอ็อบเจ็กต์สืบทอดมาจาก object ซึ่งมีเมธอด GetType() คืนค่า Type object ที่อธิบายประเภทของอินสแตนซ์ใน runtime (runtime type) ใช้สำหรับ reflection, debugging, serialization, และ type checking

ตัวอย่างโค้ดที่ 1: สตริง

using System;

public class Demo
{
    public static void Main()
    {
        string s = "Demo";
        Console.WriteLine("String = " + s);
        Console.WriteLine("String Type = " + s.GetType());
    }
}

ผลลัพธ์

String = Demo
String Type = System.String

ตัวอย่างโค้ดที่ 2: Primitive Types ต่างๆ

using System;

public class Demo
{
    public static void Main()
    {
        double val1 = 5.5;
        int val2 = 10;
        short val3 = 2;

        Console.WriteLine("Value = " + val1);
        Console.WriteLine("Value Type = " + val1.GetType());
        Console.WriteLine("Value = " + val2);
        Console.WriteLine("Value Type = " + val2.GetType());
        Console.WriteLine("Value = " + val3);
        Console.WriteLine("Value Type = " + val3.GetType());
    }
}

ผลลัพธ์

Value = 5.5
Value Type = System.Double
Value = 10
Value Type = System.Int32
Value = 2
Value Type = System.Int16

ข้อสังเกตสำคัญ

  • GetType() คืนค่า runtime type (ประเภทจริงของอ็อบเจ็กต์)
  • ต่างจาก typeof(T) ที่เป็น compile-time type
  • สำหรับ value types (int, double, struct) จะเกิด boxing เมื่อเรียก GetType()
  • คืนค่า Type object ที่มี metadata เต็มรูปแบบ (name, namespace, assembly, methods, properties, etc.)

การใช้งาน GetType() กับ Polymorphism


using System;

class Animal { }
class Dog : Animal { }
class Cat : Animal { }

public class Demo
{
    public static void Main()
    {
        Animal a1 = new Dog();
        Animal a2 = new Cat();
        
        Console.WriteLine(a1.GetType()); // Dog
        Console.WriteLine(a2.GetType()); // Cat
        Console.WriteLine(typeof(Animal)); // Animal (compile-time)
    }
}

เมธอดสำคัญของ Type Class

Memberคำอธิบาย
Nameชื่อประเภท (ไม่มี namespace)
FullNameชื่อเต็มพร้อม namespace
Namespacenamespace
AssemblyAssembly ที่ประกอบ
BaseTypeคลาสฐาน
IsClass, IsValueType, IsInterface, IsArray, IsGenericTypeตรวจสอบลักษณะประเภท
GetMethods(), GetProperties(), GetFields()Reflection members
GetConstructor(), GetMethod()หา constructor/method เฉพาะ

เคล็ดลับ

  • ใช้ obj.GetType() == typeof(MyClass) เพื่อตรวจสอบ exact type
  • ใช้ obj is MyClass หรือ obj as MyClass สำหรับ type checking ทั่วไป (รองรับ inheritance)
  • ใช้ typeof(T) เมื่อรู้ type ตอน compile-time (เร็วกว่า GetType())