zoukankan      html  css  js  c++  java
  • 反射获取属性DisplayName特性名字以及属性值

     /// <summary>
            /// 反射获取所有DisplayName标记值
            /// </summary>
            /// <typeparam name="T">实体类型</typeparam>
            /// <param name="model">需要获取的实体</param>
            /// <returns></returns>
            List<string> GetDisplayName<T>(T model)
            {
                //获取所有属性
                PropertyInfo[] properties = model.GetType().GetProperties();
    
                var list = new List<string>();
                foreach (var item in properties)
                {
                    var attrs = item.GetCustomAttributes(typeof(DisplayNameAttribute), true);
                    if (attrs != null)
                    {
                        var displayName = ((DisplayNameAttribute)attrs[0]).DisplayName;
                        list.Add(displayName);
                    }
                }
                return list;
            }
    
            /// <summary>
            /// 反射获取属性值
            /// </summary>
            /// <typeparam name="T">实体类型</typeparam>
            /// <param name="modelList">需要获取value的实体集合</param>
            /// <returns></returns>
            List<string> GetValue<T>(T modelList)
            {
                var list = new List<string>();
                var type = modelList.GetType();
                var properties = type.GetProperties();
                foreach (var item in properties)
                {
                    var pName = item.Name;
                    PropertyInfo propertyInfo = type.GetProperty(pName);
                    var value = propertyInfo.GetValue(modelList)?.ToString();
                    list.Add(value);
                }
                return list;
            }
  • 相关阅读:
    名字空间,L,E, G , B 作用域, 内置电池
    lambda表达式
    表达式与声明的区别。
    jupyter book的使用
    centos7一键安装cacti_1.2.16版本
    docker修改阿里云镜像加速器
    centos单网卡多ip,被动模式
    centos同步时间
    centos7.x制作bond
    centos 6.X制作bond
  • 原文地址:https://www.cnblogs.com/heheblog/p/10469544.html
Copyright © 2011-2022 走看看