using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace WIDESEA_Core.Helper { public static class ObjectExtension { public static List DicToIEnumerable(this List> dicList) { List list = new List(); foreach (Dictionary dic in dicList) { list.Add(dic.DicToModel()); } return list; } public static T DicToModel(this Dictionary dic) { //T model = Activator.CreateInstance(); //PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); //foreach (var property in propertyInfos) //{ // object value = null; // if (!dic.TryGetValue(property.Name, out value)) // { // if (!dic.TryGetValue(property.Name.FirstLetterToUpper(), out value)) // { // if (!dic.TryGetValue(property.Name.FirstLetterToLower(), out value)) // { // continue; // } // } // }; // property.SetValue(model, value?.ToString().ChangeType(property.PropertyType)); //} //return model; T model = Activator.CreateInstance(); PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); foreach (var property in propertyInfos) { object value = null; if (!dic.TryGetValue(property.Name, out value)) { if (!dic.TryGetValue(property.Name.FirstLetterToUpper(), out value)) { if (!dic.TryGetValue(property.Name.FirstLetterToLower(), out value)) { continue; } } } // 检查是否为空字符串 if (!string.IsNullOrEmpty(value?.ToString())) { // 将值转换为属性的类型并设置属性值 property.SetValue(model, value.ChangeType(property.PropertyType)); } } return model; } } }