发布:2023/6/25 16:45:21作者:管理员 来源:本站 浏览次数:590
1:单个实体转换
public static T2 ConvertToModel<T1, T2>(T1 source)
{
T2 model = default(T2);
PropertyInfo[] pi = typeof(T2).GetProperties();
PropertyInfo[] pi1 = typeof(T1).GetProperties();
model = Activator.CreateInstance<T2>();
foreach (var p in pi)
{
foreach (var p1 in pi1)
{
if (p.Name == p1.Name)
{
p.SetValue(model, p1.GetValue(source, null), null);
break;
}
}
}
return model;
}
2:泛型转换:
public static List<T2> ConvertToModel<T1, T2>(List<T1> list)
{
var t2 = new List<T2>();
foreach (var item in list)
{
T2 model = default(T2);
PropertyInfo[] pi = typeof(T2).GetProperties();
PropertyInfo[] pi1 = typeof(T1).GetProperties();
model = Activator.CreateInstance<T2>();
foreach (var p in pi)
{
foreach (var p1 in pi1)
{
if (p.Name == p1.Name)
{
p.SetValue(model, p1.GetValue(item, null), null);
break;
}
}
}
t2.Add(model);
}
return t2;
}