反射獲取屬性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;
        }
相關文章
相關標籤/搜索