首页 > 编程语言 > 详细

23 Enum的简单扩展

时间:2018-02-25 15:40:09      阅读:218      评论:0      收藏:0      [点我收藏+]

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:通过

 

23 Enum的简单扩展

原文:https://www.cnblogs.com/zhanhengzong/p/8469302.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!