我已经制作了基本的东西,但我坚持创建实际的 LambaExpression:
有人对我想写的内容有一些指示吗?var COPYEXPRESSION = ...
public Expression<Func<TSource, TDestination>> GetOrCreateMapExpression<TSource, TDestination>()
{
return (Expression<Func<TSource, TDestination>>)
_expressionCache.GetOrAdd(new TypePair(typeof(TSource), typeof(TDestination)), tp =>
{
return CreateMapExpression(tp.SourceType, tp.DestinationType);
});
}
private LambdaExpression CreateMapExpression(Type source, Type destination)
{
ParameterExpression instanceParameter = Expression.Parameter(source);
var sourceMembers = source.GetProperties();
var destMembers = destination.GetProperties();
var matchingMembers = sourceMembers.Select(s =>
new
{
Source = s,
Dest = destMembers.FirstOrDefault(d =>
d.Name.Equals(s.Name) && d.PropertyType == s.PropertyType)
}).Where(map => map.Dest != null).ToArray();
var COPYEXPRESSION = ...
return Expression.Lambda(COPYEXPRESSION , instanceParameter);
}
更新
我得到了正确的返回类型,但是在对此进行单元测试时,映射的类的属性为 null。
private LambdaExpression CreateMapExpression(Type source, Type destination)
{
ParameterExpression instanceParameter = Expression.Parameter(source);
var instance2Parameter = Expression.New(destination);
LabelTarget returnTarget = Expression.Label(destination);
var sourceMembers = source.GetProperties().Where(p => p.GetMethod.IsPublic);
var destMembers = destination.GetProperties().Where(p => p.SetMethod.IsPublic);
var matchingMembers = sourceMembers.Select(s =>
new
{
Source = s,
Dest = destMembers.FirstOrDefault(d =>
d.Name.Equals(s.Name) && d.PropertyType == s.PropertyType)
}).Where(map => map.Dest != null).ToArray();
var block = Expression.Block(Expression.Block(
matchingMembers.Select(p =>
Expression.Assign(
Expression.Property(instance2Parameter, p.Dest),
Expression.Property(instanceParameter, p.Source)))),
Expression.Label(returnTarget, instance2Parameter));
return Expression.Lambda(block, instanceParameter);
}
解决方案
这对我有用:
return Expression.Lambda( Expression.MemberInit(Expression.New(destination),
matchingMembers.Select(p =>
Expression.Bind(p.Dest, Expression.Property(instanceParameter, p.Source)))),
instanceParameter);