DTO:
public class Person1
{
public int Id { set; get; }
public string Name { set; get; }
public string Sex { set; get; }
}
数据源:
public class Person
{
public int Id { set; get; } = 10;
public string Name { set; get; } = "熊";
public string Sex { set; get; } = "男";
}
使用:
var person = new Person();
var persion1=B.Map<Person1, Person>(person);
工具类:
public class B
{
/// <summary>
///
/// </summary>
/// <typeparam name="R">目标实体</typeparam>
/// <typeparam name="T">数据源实体</typeparam>
/// <param name="model"></param>
/// <returns></returns>
public static R Map<R, T>(T model)
{
//动态实例化对象
R result = Activator.CreateInstance<R>();
foreach (PropertyInfo info in typeof(R).GetProperties())
{
//判断是否是相同属性
PropertyInfo pro = typeof(T).GetProperty(info.Name);
if (pro != null)
//赋值
info.SetValue(result, pro.GetValue(model));
}
return result;
}
}