实体转换类
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace AAAAA { ////// 泛型类 /// /// public class ModelConvertHelper where T : new() { /// /// 通过反射把一个类的属性的值赋值给另一个类 /// /// /// /// public static T Mapper (S s) { T d = Activator.CreateInstance(); 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; } /// /// 通过反射把一个类的属性的值赋值给另一个类 /// /// /// /// public static T MapperToString (S s) { T d = Activator.CreateInstance(); 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; } /// /// 将Dt转换成List /// /// /// public static List ConvertToModel(DataTable dt) { // 定义集合 List ts = new List (); // 获得此模型的类型 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.Mapper (ActivityData);
Listlist=ModelConvertHelper .ConvertToModel(resultDt);