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

ดึงชื่อสมาชิกของ Enumeration ใน C#

ภาพรวม

เมธอด Type.GetEnumNames() คืนค่าอาร์เรย์สตริง (string[]) ที่มีชื่อของค่าคงที่ (constants) ทั้งหมดใน enumeration เรียงตามลำดับที่ประกาศ

ตัวอย่างที่ 1: ลองกับชนิดที่ไม่ใช่ Enum (string) - โยนข้อยกเว้น

using System;

public class Demo
{
    enum Vehicle { Car, Bus, Bike }
    public static void Main()
    {
        try
        {
            Type type = typeof(string);
            string[] str = type.GetEnumNames();
            Console.WriteLine("GetEnumNames() to return the constant names = " + string.Join(", ", str));
            Console.WriteLine("Listing 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() to return the constant names = " + string.Join(", ", str));
            Console.WriteLine("Listing 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
Listing constants ..
Car Bus Bike Airplane

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

  • GetEnumNames() โยน ArgumentException หาก Type ไม่ใช่ enum
  • ชื่อที่คืนมาเรียงตามลำดับการประกาศในโค้ด (declaration order) ไม่ใช่ลำดับค่า
  • ใช้ร่วมกับ GetEnumValues() เพื่อได้ทั้งชื่อและค่า: var values = type.GetEnumValues();
  • เมธอด static เทียบเท่า: Enum.GetNames(typeof(MyEnum))
  • เหมาะสำหรับการสร้าง UI dropdown, logging, serialization ของ enum