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:通过
  • 相关阅读:
    P2018 消息传递[dp]
    P1436 棋盘分割[dp]
    一条线段引发的思考
    浅谈树上差分
    P2680 运输计划[二分+LCA+树上差分]
    P1600 天天爱跑步[桶+LCA+树上差分]
    P4560 [IOI2014]Wall 砖墙
    P1311 选择客栈[模拟]
    P1314 聪明的质监员[二分答案]
    Linux snmp导入MIB库
  • 原文地址:https://www.cnblogs.com/zhanhengzong/p/8469302.html
Copyright © 2011-2022 走看看