反射获取属性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;
        }

 

posted @ 2019-03-04 11:09  小样儿哦  阅读(2750)  评论(0编辑  收藏  举报