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

เมธอด Type.GetEnumName() ใน C#

เมธอด Type.GetEnumName() ใน C# คืนค่าชื่อของค่าคงที่ที่มีค่าที่ระบุ สำหรับประเภทการนับ (enumeration) ปัจจุบัน

ไวยากรณ์

public virtual string GetEnumName (object val);

พารามิเตอร์ val คือค่าที่ต้องการดึงชื่อ

ตัวอย่าง

ตัวอย่างที่ 1: ดึงชื่อของค่า Vehicle.Bike

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

ตัวอย่างเพิ่มเติม

ตัวอย่างที่ 2: พยายามใช้กับ string (ไม่ใช่ enum - จะโยน ArgumentException)

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