两个结构相同的实体类的转换,T2实体类的属性数可以大于T1的属性数,可用于api接口实体类参数到数据库实体的转换。
public static List<T2> CopyToList<T1, T2>(List<T1> source)
{
List<T2> t2List = new List<T2>();
T2 model = default(T2);
PropertyInfo[] pi = typeof(T2).GetProperties();
PropertyInfo[] pi1 = typeof(T1).GetProperties();
foreach (T1 t1Model in source)
{
model = Activator.CreateInstance<T2>();
for(int i=0;i<pi.Length;i++)
{
pi[i].SetValue(model, pi1[i].GetValue(t1Model, null), null);
}
t2List.Add(model);
}
return t2List;
}
public static T2 CopyToModel<T1, T2>(T1 source)
{
T2 model = default(T2);
PropertyInfo[] pi = typeof(T2).GetProperties();
PropertyInfo[] pi1 = typeof(T1).GetProperties();
model = Activator.CreateInstance<T2>();
for (int i = 0; i < pi.Length; i++)
{
pi[i].SetValue(model, pi1[i].GetValue(source, null), null);
}
return model;
}