Getting attributes of Enum's value

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

        public enum DataFilters
        {
            [Display(Name= "Equals")]
            Equals = 1,// Display Name and Enum Name are same 
            [Display(Name= "Does Not Equal")]
            DoesNotEqual = 2, // Display Name and Enum Name are different             
        }
    

    Now it will produce error in this case 1 "Equals"

    public static string GetDisplayName(this Enum enumValue)
        {
            var enumMember = enumValue.GetType().GetMember(enumValue.ToString()).First();
            return enumMember.GetCustomAttribute() != null ? enumMember.GetCustomAttribute().Name : enumMember.Name;
        }
    

    so if it is same return enum name rather than display name because enumMember.GetCustomAttribute() gets null if displayname and enum name are same.....

提交回复
热议问题