Getting attributes of Enum's value

后端 未结 25 2540
慢半拍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:26

    Adding my solution for Net Framework and NetCore.

    I used this for my Net Framework implementation:

    public static class EnumerationExtension
    {
        public static string Description( this Enum value )
        {
            // get attributes  
            var field = value.GetType().GetField( value.ToString() );
            var attributes = field.GetCustomAttributes( typeof( DescriptionAttribute ), false );
    
            // return description
            return attributes.Any() ? ( (DescriptionAttribute)attributes.ElementAt( 0 ) ).Description : "Description Not Found";
        }
    }
    

    This doesn't work for NetCore so I modified it to do this:

    public static class EnumerationExtension
    {
        public static string Description( this Enum value )
        {
            // get attributes  
            var field = value.GetType().GetField( value.ToString() );
            var attributes = field.GetCustomAttributes( false );
    
            // Description is in a hidden Attribute class called DisplayAttribute
            // Not to be confused with DisplayNameAttribute
            dynamic displayAttribute = null;
    
            if (attributes.Any())
            {
                displayAttribute = attributes.ElementAt( 0 );
            }
    
            // return description
            return displayAttribute?.Description ?? "Description Not Found";
        }
    }
    

    Enumeration Example:

    public enum ExportTypes
    {
        [Display( Name = "csv", Description = "text/csv" )]
        CSV = 0
    }
    

    Sample Usage for either static added:

    var myDescription = myEnum.Description();
    

提交回复
热议问题