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

ดึงชนิดพื้นฐาน (Underlying Type) ของ Enumeration ใน C#

ภาพรวม

เมธอด Type.GetEnumUnderlyingType() คืนค่า Type ที่แทนชนิดพื้นฐาน (underlying type) ของ enumeration ซึ่งมักเป็น int (System.Int32) แต่สามารถเป็น byte, short, long, sbyte, ushort, uint, ulong ได้

ตัวอย่างที่ 1: ดึงชนิดพื้นฐานของ Enum Vehicle

using System;

public class Demo
{
    enum Vehicle { Car, Bus, Bike, Airplane }
    public static void Main()
    {
        try
        {
            Vehicle v = Vehicle.Bike;
            Type type = v.GetType();
            string[] str = type.GetEnumNames();
            Console.WriteLine("GetEnumNames() to return the constant names = " + string.Join(", ", str));
            Type type2 = type.GetEnumUnderlyingType();
            Console.Write("Enum Underlying type = " + type2);
            Console.WriteLine("\nListing constants ..");
            for (int i = 0; i < str.Length; i++)
                Console.Write("{0} ", str[i]);
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("Not an enum!");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

ผลลัพธ์

GetEnumNames() to return the constant names = Car, Bus, Bike, Airplane
Enum Underlying type = System.Int32
Listing constants ..
Car Bus Bike Airplane

ตัวอย่างที่ 2: ลองกับชนิดที่ไม่ใช่ Enum (int)

using System;

public class Demo
{
    enum Vehicle { Car, Bus, Bike, Airplane }
    public static void Main()
    {
        try
        {
            Type type = typeof(int);
            string[] str = type.GetEnumNames();
            Console.WriteLine("GetEnumNames() to return the constant names = " + string.Join(", ", str));
            Type type2 = type.GetEnumUnderlyingType();
            Console.Write("Enum Underlying type = " + type2);
            Console.WriteLine("\nListing constants ..");
            for (int i = 0; i < str.Length; i++)
                Console.Write("{0} ", str[i]);
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("Not an enum!");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

ผลลัพธ์

Not an enum!
System.ArgumentException

คำอธิบายเพิ่มเติม

  • GetEnumUnderlyingType() โยน ArgumentException หาก Type ไม่ใช่ enumeration
  • Enum ค่าเริ่มต้นใช้ int เป็น underlying type สามารถระบุชนิดอื่นได้: enum MyEnum : byte { A, B }
  • GetEnumNames() คืนค่าอาร์เรย์ชื่อค่าคงที่ (constant names) ของ enum
  • GetEnumValues() คืนค่าอาร์เรย์ค่าของ enum (ใช้สำหรับวนลูปค่าได้)
  • ใช้ Enum.GetUnderlyingType(typeof(MyEnum)) เป็นทางเลือก static method