How to get all descriptions of enum values with reflection?

前端 未结 7 1479
孤独总比滥情好
孤独总比滥情好 2021-02-10 08:29

So I need to get a List from my enum

Here is what I have done so far:

enum definition

           


        
7条回答
  •  天涯浪人
    2021-02-10 09:08

    It think this can solve your problem. If it is not implemented you can return null or an exception. It depends what you need.

    public DescriptionAttribute GetDescription(ContractorType contractorType)
    {
         MemberInfo memberInfo = typeof(ContractorType).GetMember(contractorType.ToString())
                                              .FirstOrDefault();
    
         if (memberInfo != null)
        {
             DescriptionAttribute attribute = (DescriptionAttribute) 
                     memberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false)
                               .FirstOrDefault();
             return attribute;
        }
    
        //return null;
        //or
    
        throw new NotImplementedException("There is no description for this enum");
    }
    

    So you will use it like this :

    DescriptionAttribute attribute = GetDescription(ContractorType.RECIPIENT);
    

    Sorry that I didn't read your question. Here is some code that you can use to take all of the description strings:

     public IEnumerable GetAllDescriptionInText()
     {
         List descList = new List();
         foreach (DescriptionAttribute desc in Enum.GetValues(typeof(DescriptionAttribute)))
         {
             descList.Add(GetDescription(desc).Value);
         }
         return descList;
     }
    

提交回复
热议问题