1:构建实体,(注意:属性数量一样)
public class C1
{
public string age { get; set; }
public string name { get; set; }
}
public class C2
{
public string 年龄 { get; set; }
public string 姓名 { get; set; }
}
2:填充数据:
var list = new List<C1>();
list.Add(new C1
{
age = "11",
name = "admin"
});
list.Add(new C1
{
age = "22",
name = "张三"
});
3:方法调用: var newlist = ConvertToNewModel<C1, C2>(list);
4:方法:
public static List<T2> ConvertToNewModel<T1, T2>(List<T1> list)
{
var t2 = new List<T2>();
foreach (var item in list)
{
T2 model = default(T2);
model = Activator.CreateInstance<T2>();
PropertyInfo[] pi1 = typeof(T1).GetProperties();
PropertyInfo[] propertys = model.GetType().GetProperties();
for (int i = 0; i < propertys.Count(); i++)
{
propertys[i].SetValue(model, pi1[i].GetValue(item, null), null);
}
t2.Add(model);
}
return t2;
}