Type.GetEnumName() วิธีการใน C# ส่งกลับชื่อของค่าคงที่ที่มีค่าที่ระบุ สำหรับประเภทการแจงนับปัจจุบัน
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
public virtual string GetEnumName (object val);
ด้านบน Val คือค่าที่ต้องการเรียกชื่อ
ตัวอย่าง
ให้เราดูตัวอย่างการใช้เมธอด 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);
}
} ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
GetEnumName() to return the constant name = Bike
ตัวอย่าง
ให้เราดูตัวอย่างอื่นเพื่อนำวิธีการ 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);
}
}
} ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
Not an enum! System.ArgumentException