Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức Type.GetEnumName() trong C#

Phương thức Type.GetEnumName() trong C# trả về tên hằng số có giá trị được chỉ định cho kiểu enum hiện tại.

Cú pháp

public virtual string GetEnumName(object val);

Tham số val là giá trị cần lấy tên.

Ví dụ 1

using System;
public class Demo
{
    public 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

GetEnumName() to return the constant name = Bike

Ví dụ 2

using System;
public class Demo
{
    public 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

Not an enum! System.ArgumentException