Enum的简单扩展

1 添加一个描述的Attribute

    public enum MessageResult
    {
        [System.ComponentModel.Description("未通过")]
        UnPass = 0,
        [System.ComponentModel.Description("通过")]
        Pass = 1,
    }

2 添加扩展方法

    public static class EnumExtension
    {
        private static readonly ConcurrentDictionary<string, Dictionary<object, string>> EnumDescriptions
            = new ConcurrentDictionary<string, Dictionary<object, string>>();

        public static Dictionary<object, string> AsValueDesDic(this Type enumType, bool nameAsEmptyDes = false)
        {
            Trace.Assert(enumType.IsEnum);
            Func<Type, Dictionary<object, string>> builder = type =>
            {
                var dic = new Dictionary<object, string>();
                foreach (var i in Enum.GetValues(type))
                {
                    var name = Enum.GetName(type, i);
                    var filed = type.GetField(name);
                    var attr = filed.GetCustomAttributes<System.ComponentModel.DescriptionAttribute>()
                        .FirstOrDefault();
                    if (attr != null)
                        dic.Add(i, attr.Description);
                    else if (nameAsEmptyDes)
                        dic.Add(i, name);
                }

                return dic;
            };
            return EnumDescriptions.GetOrAdd(enumType.FullName, key => builder(enumType));
        }
    }

3 使用方式

           var a = typeof(MessageResult).AsValueDesDic();
            foreach (var item in a)
            {
                Trace.WriteLine((int)item.Key+":"+item.Value);
            }

4 输出内容

Debug Trace:
0:未通过
1:通过

 

posted @ 2018-02-25 14:19  ZhanHengZong  阅读(286)  评论(0编辑  收藏  举报