在调用接口的时候,发现二个类型的属性几乎全部相同,并且属性很多,现在需要将一个类型转换为另一个类型,并将相同属性赋值给另一个,一个个去写,浪费时间,需要抽象出一个函数,用到反射,记录一下。
public D Mapper<D, S>(S s)
{
D d = Activator.CreateInstance<D>();
try
{
var sType = s.GetType(); var dType = typeof(D);
foreach (PropertyInfo sP in sType.GetProperties())
{
foreach (PropertyInfo dP in dType.GetProperties())
{
if (dP.Name == sP.Name)
{
dP.SetValue(d, sP.GetValue(s, null), null);
}
}
}
}
catch (Exception ex) { } return d;
}