核心代码
/// <summary> /// 属性重复值复制 /// </summary> /// <typeparam name="V">源模型</typeparam> /// <typeparam name="T">目标模型</typeparam> /// <param name="sourceList">数据源</param> /// <returns></returns> public static List<T> ConvertData<V, T>(List<V> sourceList) { List<T> list = new List<T>(); Type type = typeof(T); PropertyInfo[] properties = type.GetProperties();//获取目标模型属性 foreach (V item in sourceList) { T model = Activator.CreateInstance<T>(); //创建目标模型实例 for (int i = 0; i < properties.Length; i++) { PropertyInfo[] personPro = item.GetType().GetProperties(); for (int j = 0; j < personPro.Length; j++) { //判断目标模型的属性是不是源模型中的 if (properties[i].Name == personPro[j].Name && properties[i].PropertyType == personPro[j].PropertyType) { Object value = personPro[j].GetValue(item, null); //将源模型中属性的值赋值给目标模型的属性 properties[i].SetValue(model, value, null); } } } list.Add(model); } return list; }
测试:
类Test1
public string ID { get; set; } public string Name { get; set; } public string Sex { get; set; } public string Address { get; set; }
类Test2
public string ID { get; set; } public string Name { get; set; } public string Sex { get; set; }
调用
List<Test1> testList = new List<Test1> { new Test1 { ID = "1", Name = "王二狗", Sex = "男", Address="12" }, new Test1 { ID = "2", Name = "王狗", Sex = "男", Address="12" } }; List<Test2> list = new List<Test2>(); list = ConvertData<Test1, Test2>(testList);