本文介绍了防爆pression树复制或转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何转换格式的防爆pressionTree
How to convert a ExpressionTree of form
Expression<Func<POCO1, bool>> exp = p => p.Age > 50;
到
Expression<Func<POCO2, bool>> exp2 = p => p.Age > 50;
在这里POCO1和POCO2是C#对象,并都有的Int32 Age属性。
where POCO1 and POCO2 are C# objects and both have Int32 Age property
推荐答案
很好,你可以进行自定义前pression游客,将取代参数引用和补丁成员访问前pressions
well, you can make custom expression visitor that will replace parameter references and patch member access expressions
class Converter<TTo>
{
class ConversionVisitor : ExpressionVisitor
{
private readonly ParameterExpression newParameter;
private readonly ParameterExpression oldParameter;
public ConversionVisitor(ParameterExpression newParameter, ParameterExpression oldParameter)
{
this.newParameter = newParameter;
this.oldParameter = oldParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return newParameter; // replace all old param references with new ones
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression != oldParameter) // if instance is not old parameter - do nothing
return base.VisitMember(node);
var newObj = Visit(node.Expression);
var newMember = newParameter.Type.GetMember(node.Member.Name).First();
return Expression.MakeMemberAccess(newObj, newMember);
}
}
public static Expression<Func<TTo, TR>> Convert<TFrom, TR>(
Expression<Func<TFrom, TR>> e
)
{
var oldParameter = e.Parameters[0];
var newParameter = Expression.Parameter(typeof(TTo), oldParameter.Name);
var converter = new ConversionVisitor(newParameter, oldParameter);
var newBody = converter.Visit(e.Body);
return Expression.Lambda<Func<TTo, TR>>(newBody, newParameter);
}
}
class A
{
public int Value { get; set; }
}
class B
{
public int Value { get; set; }
}
Expression<Func<A, int>> f = x => x.Value;
var f2 = Converter<B>.Convert(f);
这篇关于防爆pression树复制或转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!