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

การดึงอาร์เรย์ค่าคงที่ของ Enum ใน C#

ภาพรวม

Type.GetEnumValues() คืนค่า Array ของค่าคงที่ทั้งหมดใน Enum ต้องใช้กับ Type ที่เป็น Enum เท่านั้น มิฉะนั้นโยน ArgumentException

ตัวอย่างที่ 1: พยายามใช้กับ int (ไม่ใช่ Enum) - โยน Exception

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() = " + str);

            Type type2 = type.GetEnumUnderlyingType();
            Console.Write("Enum Underlying type = " + type2);

            Array arrObj = type.GetEnumValues();
            Console.Write("Values = {0}" + arrObj);

            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

ตัวอย่างที่ 2: ใช้กับ 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() = " + str);

            Type type2 = type.GetEnumUnderlyingType();
            Console.Write("Enum Underlying type = " + type2);

            Array arrObj = type.GetEnumValues();
            Console.Write("Values = " + arrObj);

            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 name = System.String[]
Enum Underlying type = System.Int32
Values = Demo+Vehicle[]
Listing constants ..
Car Bus Bike Airplane

สรุป

  • GetEnumValues() ต้องใช้กับ Type ที่เป็น Enum เท่านั้น
  • คืนค่า Array ของค่าคงที่ (underlying type ปกติคือ int)
  • คู่กับ GetEnumNames() (ชื่อ) และ GetEnumUnderlyingType() (ชนิดพื้นฐาน)
  • ใช้ typeof(EnumType) หรือ enumValue.GetType() ได้ Type ที่ถูกต้อง