Phương thức Type.GetEnumName () trong C # trả về tên của hằng số có giá trị được chỉ định cho kiểu liệt kê hiện tại.
Cú pháp
Sau đây là cú pháp -
public virtual string GetEnumName (object val);
Ở trên, Val là giá trị có tên sẽ được truy xuất.
Ví dụ
Bây giờ chúng ta hãy xem một ví dụ để triển khai phương thức Type.GetEnumName () -
using System;
public class Demo {
enum Vehicle {Car, Bus, Bike}
public static void Main(){
Vehicle v = Vehicle.Bike;
Type type = v.GetType();
string str = type.GetEnumName(v);
Console.WriteLine("GetEnumName() to return the constant name = " + str);
}
} Đầu ra
Điều này sẽ tạo ra kết quả sau -
GetEnumName() to return the constant name = Bike
Ví dụ
Bây giờ chúng ta hãy xem một ví dụ khác để triển khai phương thức Type.GetEnumName () -
using System;
public class Demo {
enum Vehicle {Car, Bus, Bike}
public static void Main(){
try {
Vehicle v = Vehicle.Bike;
Type type = typeof(string);
string str = type.GetEnumName(v);
Console.WriteLine("GetEnumName() to return the constant name = " + str);
}
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