Getting Description Attribute of a Generic Enum

前端 未结 3 1954
臣服心动
臣服心动 2021-01-14 05:30

I\'m having some hard time with trying to be generic with enums. I\'ve read that it\'s not that simple, and I can\'t seem to find a solution.

I\'m trying to create a

3条回答
  •  清酒与你
    2021-01-14 06:04

    Here, try this:

    public static KeyValuePair> ConvertEnumWithDescription() where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
            {
                throw new Exception("Type given T must be an Enum");
            }
    
            var enumType = typeof(T).ToString().Split('.').Last();
            var itemsList = Enum.GetValues(typeof(T))
                  .Cast()
                   .Select(x => new KeyValueDataItem
                   {
                       Key = Convert.ToInt32(x),
                       Value = GetEnumDescription(x.ToString())
                   })
                   .ToList();
    
            var res = new KeyValuePair>(
                enumType, itemsList);
            return res;
    
        }
    
        public static string GetEnumDescription(string value)
        {
            Type type = typeof(T);
            var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
    
            if (name == null)
            {
                return string.Empty;
            }
            var field = type.GetField(name);
            var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
    }
    

    Based on: http://www.extensionmethod.net/csharp/enum/getenumdescription

提交回复
热议问题