using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace AAAAA { /// <summary> /// 泛型类 /// </summary> /// <typeparam name="T"></typeparam> public class ModelConvertHelper<T> where T : new() { /// <summary> /// 通过反射把一个类的属性的值赋值给另一个类 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="S"></typeparam> /// <returns></returns> public static T Mapper<S>(S s) { T d = Activator.CreateInstance<T>(); var sType = s.GetType(); var dType = typeof(T); foreach (PropertyInfo sP in sType.GetProperties()) { foreach (PropertyInfo dP in dType.GetProperties()) { if (dP.Name == sP.Name) { if (dP.PropertyType.Name == typeof(string).Name && sP.GetValue(s) == null) { dP.SetValue(d, string.Empty); } else { dP.SetValue(d, sP.GetValue(s)); } } } } return d; } /// <summary> /// 通过反射把一个类的属性的值赋值给另一个类 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="S"></typeparam> /// <returns></returns> public static T MapperToString<S>(S s) { T d = Activator.CreateInstance<T>(); var sType = s.GetType(); var dType = typeof(T); foreach (PropertyInfo sP in sType.GetProperties()) { foreach (PropertyInfo dP in dType.GetProperties()) { if (dP.Name == sP.Name) { if (sP.GetValue(s) != null) { dP.SetValue(d, sP.GetValue(s).ToString()); } } } } return d; } /// <summary> /// 将Dt转换成List /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<T> ConvertToModel(DataTable dt) { // 定义集合 List<T> ts = new List<T>(); // 获得此模型的类型 Type type = typeof(T); string tempName = ""; foreach (DataRow dr in dt.Rows) { T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName)) { // 判断此属性是否有Setter if (!pi.CanWrite) continue; //属性赋值 object value = dr[tempName]; if (value != DBNull.Value) { pi.SetValue(t, value); } else if (pi.PropertyType.Name == typeof(string).Name) { pi.SetValue(t, string.Empty); } } } ts.Add(t); } return ts; } } }
调用
ActivityDataResult model=ModelConvertHelper<ActivityDataResult>.Mapper<HPR_ActivityData>(ActivityData);
List<RSDUserInfo>list=ModelConvertHelper<RSDUserInfo>.ConvertToModel(resultDt);