Computer >> Máy Tính >  >> Lập trình >> C#

Lấy tên của các thành viên của kiểu liệt kê hiện tại trong C #

Để lấy tên của các thành viên của kiểu liệt kê hiện tại, mã như sau -

Ví dụ

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("GetEnumName() to return the constant name = " + 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);
      }
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Not an enum!
System.ArgumentException

Ví dụ

Hãy để chúng tôi xem một ví dụ khác -

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("GetEnumName() to return the constant name = " + 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);
      }
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

GetEnumName() to return the constant name = System.String[]
Listing constants ..
Car Bus Bike airplane