Giới thiệu
Phương thức Type.GetEnumNames() trả về mảng chuỗi chứa tên tất cả các hằng số trong enum. Phải gọi trên Type của enum (lấy qua typeof(EnumType) hoặc enumValue.GetType()).
Ví dụ 1: Thử với kiểu không phải 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() = " + 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);
}
}
}
Kết quả
Not an enum! System.ArgumentException
Ví dụ 2: Lấy tên thành viên từ enum hợp lệ
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() = " + 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);
}
}
}
Kết quả
GetEnumNames() = Car, Bus, Bike, Airplane Listing constants .. Car Bus Bike Airplane
Các phương thức liên quan của Type cho Enum
| Phương thức | Trả về | Mô tả |
|---|---|---|
| GetEnumNames() | string[] | Tên các hằng số |
| GetEnumValues() | Array | Giá trị các hằng số (có thể cast) |
| GetEnumUnderlyingType() | Type | Kiểu nền tảng (int, byte...) |
| IsEnumDefined(name/value) | bool | Kiểm tra tên/giá trị có trong enum |
| GetEnumName(value) | string | Tên hằng số từ giá trị |
Ví dụ thực dụng: Duyệt enum
enum Priority { Low = 1, Medium = 2, High = 3, Critical = 4 }
foreach (string name in Enum.GetNames(typeof(Priority)))
{
var value = Enum.Parse(typeof(Priority), name);
Console.WriteLine($"{name} = {(int)value}");
}
// Hoặc dùng GetValues
foreach (Priority p in Enum.GetValues(typeof(Priority)))
{
Console.WriteLine($"{p} = {(int)p}");
}
Lưu ý
- Luôn kiểm tra
type.IsEnumtrước khi gọi các phương thức Enum - Thứ tự trả về theo thứ tự khai báo trong code
- Enum flags ([Flags]) cũng hoạt động bình thường