/// <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; }
原文地址:https://www.cnblogs.com/lonelyxmas/p/10474503.html
时间: 2024-10-11 11:43:17