zoukankan      html  css  js  c++  java
  • 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:通过
  • 相关阅读:
    __autoload函数
    错误处理try catch
    PHP面向对象基础实例
    类的继承关系实例
    YII重点文件
    //计算今年月度利息和
    cookie保存分页参数
    win64(win8)的python拓展包安装经验总结
    matcom安装时无法寻找到matlab.exe的解决办法
    《人人都是产品经理》阅读笔记一
  • 原文地址:https://www.cnblogs.com/zhanhengzong/p/8469302.html
Copyright © 2011-2022 走看看