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:通过
  • 相关阅读:
    css
    ubuntu 解压zip 文件乱码
    常用 Git 命令清单
    phpstorm git配置
    github ssh秘钥配置
    ubuntu 安装phpunit
    ubuntu 安装php xdebug
    nginx压缩,缓存
    mysql中max_allowed_packet参数的配置方法(避免大数据写入或者更新失败)
    putty登录显示IP
  • 原文地址:https://www.cnblogs.com/zhanhengzong/p/8469302.html
Copyright © 2011-2022 走看看