Enum ToString with user friendly strings

后端 未结 23 2141
伪装坚强ぢ
伪装坚强ぢ 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:22

    For flags enum including.

        public static string Description(this Enum value)
        {
            Type type = value.GetType();
    
            List res = new List();
            var arrValue = value.ToString().Split(',').Select(v=>v.Trim());
            foreach (string strValue in arrValue)
            {
                MemberInfo[] memberInfo = type.GetMember(strValue);
                if (memberInfo != null && memberInfo.Length > 0)
                {
                    object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                    if (attrs != null && attrs.Length > 0 && attrs.Where(t => t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault() != null)
                    {
                        res.Add(((DescriptionAttribute)attrs.Where(t => t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault()).Description);
                    }
                    else
                        res.Add(strValue);
                }
                else
                    res.Add(strValue);
            }
    
            return res.Aggregate((s,v)=>s+", "+v);
        }
    

提交回复
热议问题