/// /// 反射獲取所有DisplayName標記值 /// /// 實體類型 /// 需要獲取的實體 /// List GetDisplayName(T model) { //獲取所有屬性 PropertyInfo[] pr... ...
/// <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; }