定义两个对象
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class NewPerson
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
创建表达式树转换器
public class ExpressionMapper<TIn, TOut>
{
private static Func<TIn, TOut> _mapper = null;
static ExpressionMapper()
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "x");
List<MemberBinding> bindings = new List<MemberBinding>();
foreach (var property in typeof(TOut).GetProperties())
{
MemberExpression member = Expression.Property(parameterExpression, typeof(TIn).GetProperty(property.Name));
MemberBinding binding = Expression.Bind(property, member); // x=>x.Id
bindings.Add(binding);
}
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), bindings.ToArray()); //new newPersion(){Id=x.Id,Name=x.Name,Age=x.Aget}
var funcExp = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, parameterExpression); // x=> new newPersion(){Id=x.Id,Name=x.Name,Age=x.Aget}
_mapper = funcExp.Compile();
}
public static TOut Mapper(TIn sour)
{
return _mapper(sour);
}
}
源对象转换为目标对象
var person = new Person()
{
Id = 1,
Name = "张三",
Age = 2
};
var newPersion = ExpressionMapper<Person, NewPerson>.Mapper(person);
标签:set,Name,get,对象,public,转换器,Expression,Id,表达式
From: https://www.cnblogs.com/SSprite/p/17287913.html