Enum to list as an extension?

后端 未结 6 1309
花落未央
花落未央 2021-02-19 19:00

I have various enums that I use as sources for dropdown lists, In order to provide for a user-friendly description, I added a Description attribute to each enum, an

6条回答
  •  失恋的感觉
    2021-02-19 19:41

    Another take on this:

    class Program
    {
        //Example enum
        public enum eFancyEnum
        {
            [Description("Obsolete")]
            Yahoo,
            [Description("I want food")]
            Meow,
            [Description("I want attention")]
            Woof,
        }
        static void Main(string[] args)
        {
            //This is how you use it
            Dictionary myDictionary = typeof(eFancyEnum).ToDictionary();
        }
    }
    
    public static class EnumExtension
    {
        //Helper method to get description
        public static string ToDescription(this T en)
        {
             Type type = en.GetType();
             MemberInfo[] memInfo = type.GetMember(en.ToString());
             if (memInfo != null && memInfo.Length > 0)
             {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                   return ((DescriptionAttribute)attrs[0]).Description;
             }
             return en.ToString();
        }
    
        //The actual extension method that builds your dictionary
        public static Dictionary ToDictionary(this Type source) where T : struct, IConvertible
        {
             if(!source.IsEnum || typeof(T) != source)
             {
                throw new InvalidEnumArgumentException("BOOM");
             }
    
             Dictionary retVal = new Dictionary();
    
             foreach (var item in Enum.GetValues(typeof(T)).Cast())
              {
                retVal.Add(item, item.ToDescription());
              }
    
             return retVal;
        }
    }
    

提交回复
热议问题