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:通过
  • 相关阅读:
    tr加不上边框
    placeholder 用法
    <input/>文本输入框效果:
    colspan="2"、列、rowspan="3"、行、用法!
    CSS--实现小三角形
    “div+css”下拉菜单
    HDU4624 Endless Spin(概率&&dp)
    chanme的博客搬家了!
    HDU5487 Difference of Languages(BFS)
    HDU5469 Antonidas(树分治&&哈希)
  • 原文地址:https://www.cnblogs.com/zhanhengzong/p/8469302.html
Copyright © 2011-2022 走看看