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

C# Enum.GetType() Method: ดึงประเภทของ Enumeration

เมธอด GetType() (จาก Object) ใช้ดึง Type Object ของ Enum Instance ร่วมกับ Enum.GetUnderlyingType() เพื่อดู Underlying Type (int, byte, short, etc.)

ตัวอย่าง

using System;

public class Demo
{
    public static void Main()
    {
        // Enum Array ที่มีประเภทต่างกัน
        Enum[] values = { ConsoleColor.Blue, DayOfWeek.Sunday };
        
        Console.WriteLine("{0,-15} {1, -15} {2, -15}", "Member", "Enumeration", "UnderlyingType");
        
        foreach (var val in values)
        {
            Info(val);
        }
    }
    
    static void Info(Enum val)
    {
        Type enumType = val.GetType();                    // Type ของ Enum (เช่น ConsoleColor)
        Type underlyingType = Enum.GetUnderlyingType(enumType); // Underlying Type (เช่น Int32)
        
        Console.WriteLine("{0, -15} {1, -15} {2, -15}", val, enumType.Name, underlyingType.Name);
    }
}

ผลลัพธ์

Member          Enumeration     UnderlyingType
Blue            ConsoleColor    Int32
Sunday          DayOfWeek       Int32

คำอธิบาย

  • val.GetType() - ส่งคืน RuntimeType ของ Enum คอนกรีต (เช่น ConsoleColor)
  • Enum.GetUnderlyingType(enumType) - ส่งคืน Primitive Type ที่เก็บค่า (ส่วนใหญ่คือ Int32)
  • ใช้ typeof(MyEnum) ได้โดยไม่ต้องมี Instance

การใช้งานเพิ่มเติม

enum Priority : byte { Low, Medium, High }

// ดึง Underlying Type โดยไม่ต้องมี Instance
Type underlying = Enum.GetUnderlyingType(typeof(Priority));
Console.WriteLine(underlying.Name); // Byte

// ตรวจสอบ Underlying Type
if (underlying == typeof(byte))
    Console.WriteLine("Memory Efficient!");

ประโยชน์: ตรวจสอบ Underlying Type สำหรับ Serialization, Database Mapping, Interop, Memory Optimization