c#通过ExpressionTree 表达式树实现对象关系映射

//反射+expression实现对象自动映射

void Main()
{
	Person p1=new(){
		Id=1,
		Name="abc"
	};

	var persondto = p1.MapTo<Person, PersonDto>();
	Console.WriteLine($"id:{persondto.Id}-name:{persondto.Name}");
}

public static class AutoMapperExs
{
public static TDest MapTo<TSource, TDest>(this TSource source) where TSource : class, new() where TDest : class, new()
{

//Expression> exp = person => new PersonDto {Id=person.Id,Name=person.Name};
var destType = typeof(TDest);
var sourceType = typeof(TSource);
//1.创建参数表达式
var parameterExpression = Expression.Parameter(sourceType, "person");
//2.获取所有源类型的属性
var sourceProps = sourceType.GetProperties();
//保存所有属性的绑定关系
List<MemberBinding> list = new();
foreach (var sourceProp in sourceProps)
{
//3.创建成员表达式 person.Id,person.name
var memberExpression = Expression.Property(parameterExpression, sourceProp);
//成员绑定 Id=person.Id
var meberBingding = Expression.Bind(destType.GetProperty(sourceProp.Name), memberExpression);
list.Add(meberBingding);

}
//5.创建对象表达式:new pesonDto()
var destExpression = Expression.New(destType);
//6.成员初始化表达式:new PersonDto{Id=person.Id,Name=person.Name}
var memberInitExpression = Expression.MemberInit(destExpression, list);
//7.创建最终的表达式
var expression = Expression.Lambda<Func<TSource, TDest>>(memberInitExpression, parameterExpression);
var compile = expression.Compile();
return compile.Invoke(source);
}
}


class Person
{
	public int Id { get; set; }
	public string Name { get; set; }
}
class PersonDto
{
	public int Id { get; set; }
	public string Name { get; set; }
}

你可能感兴趣的:(c#基础,c#)