zoukankan      html  css  js  c++  java
  • C# net 遍历枚举和特性(Attribute)

    C# net 遍历 枚举 特性 Attribute 

    C# net 遍历 枚举 enum 特性 Attribute 

    net 遍历 枚举 enum 特性 Attribute 

    假如我们有如下枚举

        /// <summary>
        /// 角色
        /// </summary>
        public enum Role
        {
            /// <summary>
            /// 超级管理员
            /// </summary>
            [Description("超级管理员")]
            Admin = 0,
            /// <summary>
            /// 租借用户
            /// </summary>
            [Description("租借用户")]
            Lease = 1,
            /// <summary>
            /// 普通购买用户
            /// </summary>
            [Description("普通购买用户")]
            Money = 2,
        }

    我们想获取到 3个参数  {["Admin",0,"超级管理员"],["Lease",...]} 怎么办呢?

    代码如下

            public static void Gets(Type type)
            {
                if (type.IsEnum)
                {
                    var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public) ?? new FieldInfo[] { };
                    foreach (var field in fields)
                    {
                        //取到:Admin
                        var name = field.Name;
                        //取到:0
                        var val = (int)field.GetValue(null);
    
                        var atts = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (atts != null && atts.Length > 0)
                        {
                            //取到:超级管理员
                            var att = ((DescriptionAttribute[])atts)[0];
                            var des = att.Description;
                        }
                    }
                }
                else
                {
    
                }
            }

    调用方法,如下:

    Gets(typeof(Role));

    完成!

    补充:如果需要获取单个枚举的值,参考 https://www.cnblogs.com/ping9719/p/15699109.html

    如有问题请联系QQ: var d=["1","2","3","4","5","6","7","8","9"]; var pass=d[8]+d[6]+d[0]+d[8]+d[2]+d[0]+d[4]+d[3]+d[2];
  • 相关阅读:
    BZOJ2243: [SDOI2011]染色
    BZOJ1036: [ZJOI2008]树的统计Count
    转自 x_x_的百度空间 搞ACM的你伤不起
    wcf test client
    wcf test client
    log4net编译后命名空间找不到的问题
    log4net编译后命名空间找不到的问题
    Hive Getting Started
    Hive Getting Started
    刚听完CSDN总裁蒋涛先生的学术报告
  • 原文地址:https://www.cnblogs.com/ping9719/p/15698921.html
Copyright © 2011-2022 走看看