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,
        }

    我们想获取某一个的值和特性,如 {"Lease",1,"租借用户"}

    调用方法:

    Get(Role.Lease)

    实现代码:

            public static void Get(Enum obj)
            {
                if (obj == null)
                    return;
    
                var type = obj.GetType();
                //获取到:Admin
                var enumName = Enum.GetName(type, obj);
                var field = type.GetField(enumName);
                //获取到: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;
                }
            }

    完成

    补:如需要遍历枚举请参考此文章 https://www.cnblogs.com/ping9719/p/15698921.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];
  • 相关阅读:
    gym 101480 Problem C: Cow Confinement 题解
    Uva 1072 Huffman Codes 题解
    NERC 2015 Hypercube 题解
    ACM ICPC 2017 WF Problem J Son of Pipe Stream题解
    CF Round # 295 (Div. 1)题解
    CF 1444 D Rectangular Polyline 题解
    BZOJ3308 九月的咖啡店
    BZOJ4025 二分图
    BZOJ4000 [TJOI2015]棋盘
    BZOJ3999 [TJOI2015]旅游
  • 原文地址:https://www.cnblogs.com/ping9719/p/15699109.html
Copyright © 2011-2022 走看看