Getting attributes of Enum's value

后端 未结 25 2574
慢半拍i
慢半拍i 2020-11-22 00:35

I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following <

25条回答
  •  花落未央
    2020-11-22 01:13

    Fluent one liner...

    Here I'm using the DisplayAttribute which contains both the Name and Description properties.

    public static DisplayAttribute GetDisplayAttributesFrom(this Enum enumValue, Type enumType)
    {
        return enumType.GetMember(enumValue.ToString())
                       .First()
                       .GetCustomAttribute();
    }
    

    Example

    public enum ModesOfTransport
    {
        [Display(Name = "Driving",    Description = "Driving a car")]        Land,
        [Display(Name = "Flying",     Description = "Flying on a plane")]    Air,
        [Display(Name = "Sea cruise", Description = "Cruising on a dinghy")] Sea
    }
    
    void Main()
    {
        ModesOfTransport TransportMode = ModesOfTransport.Sea;
        DisplayAttribute metadata = TransportMode.GetDisplayAttributesFrom(typeof(ModesOfTransport));
        Console.WriteLine("Name: {0} \nDescription: {1}", metadata.Name, metadata.Description);
    }
    

    Output

    Name: Sea cruise 
    Description: Cruising on a dinghy
    

提交回复
热议问题