Enum ToString with user friendly strings

后端 未结 23 1805
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:44

My enum consists of the following values:

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

I want to be able to

23条回答
  •  太阳男子
    2020-11-22 12:26

    Even cleaner summary:

    using System;
    using System.Reflection;
    
    public class TextAttribute : Attribute
    {
        public string Text;
        public TextAttribute(string text)
        {
            Text = text;
        }
    }  
    
    public static class EnumExtender
    {
        public static string ToText(this Enum enumeration)
        {
            var memberInfo = enumeration.GetType().GetMember(enumeration.ToString());
            if (memberInfo.Length <= 0) return enumeration.ToString();
    
            var attributes = memberInfo[0].GetCustomAttributes(typeof(TextAttribute), false);
            return attributes.Length > 0 ? ((TextAttribute)attributes[0]).Text : enumeration.ToString();
        }
    }
    

    Same usage as underscore describes.

提交回复
热议问题