如何将一种类型的表达式树转换为不同的表达式类型? [英] How do I translate an expression tree of one type to a different expression type?

查看:14
本文介绍了如何将一种类型的表达式树转换为不同的表达式类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个几乎相同的类 AnimalAnimalViewModel 以及与视图模型相关的表达式树,我如何将其转换为 Animal?

If I have two nearly identical classes Animal and AnimalViewModel and an expression tree related to the viewmodel, how can I translate it to Animal?

public class Animal
{
   public string Species { get; set; }
   public string Name { get; set; }
   public string Sound { get; set; }
}
public class AnimalViewModel : ViewModelBase
{
   public string Species { get; set; }
   public string Name { get; set; }
   public string Sound { get; set; }
}

如何将 Expression> 转换为 Expression>?

public static Expression<Func<Animal,bool>> Translate (Expression<Func<AnimalViewModel,bool>> expression)
{
  // What goes here?  I assume I have to traverse the tree somehow.
}

推荐答案

这里有一位访客在做这项工作.

Here's a visitor that does the job.

  • 它制作参数的副本(因为我们需要创建一个新参数并将旧参数的所有引用替换为新参数)
  • 它遍历树的 .Body,替换参数,并将针对 old 类型的任何成员访问切换到 上的同名成员>新类型
  • 它使用我们在earler中发明的参数重新组装了一个lambda
  • it makes a copy of the parameter (since we'll need to create a new parameter and substitute all references of the old parameter for the new one)
  • it walks the .Body of the tree, substituting the parameter, and switching any member-access against the old type to a like-named member on the new type
  • it re-assembles a lambda using the parameter we invented earler

代码:

class TypeChangeVisitor : ExpressionVisitor
{
    private readonly Type from, to;
    private readonly Dictionary<Expression, Expression> substitutions;
    public TypeChangeVisitor(Type from, Type to, Dictionary<Expression, Expression> substitutions)
    {
        this.from = from;
        this.to = to;
        this.substitutions = substitutions;
    }
    public override Expression  Visit(Expression node)
    { // general substitutions (for example, parameter swaps)
        Expression found;
        if(substitutions != null && substitutions.TryGetValue(node, out found))
        {
            return found;
        }
        return base.Visit(node);
    }
    protected override Expression VisitMember(MemberExpression node)
    { // if we see x.Name on the old type, substitute for new type
        if (node.Member.DeclaringType == from)
        {
            return Expression.MakeMemberAccess(Visit(node.Expression),
                to.GetMember(node.Member.Name, node.Member.MemberType,
                BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Single());
        }
        return base.VisitMember(node);
    }
}
public class Program
{
    public static void Main()
    {
        Expression<Func<AnimalViewModel, bool>> predicate = x => x.Name == "abc";
        var switched = Translate<AnimalViewModel, Animal>(predicate);
    }
    public static Expression<Func<TTo, bool>> Translate<TFrom, TTo>(Expression<Func<TFrom, bool>> expression)
    {
        var param = Expression.Parameter(typeof(TTo), expression.Parameters[0].Name);
        var subst = new Dictionary<Expression, Expression> { { expression.Parameters[0], param } };
        var visitor = new TypeChangeVisitor(typeof(TFrom), typeof(TTo), subst);
        return Expression.Lambda<Func<TTo, bool>>(visitor.Visit(expression.Body), param);
    }
}

请注意,如果您有 x.Something.Name,您可能需要更加小心,但这应该能让您找到一个合理的方法.

Note that if you have x.Something.Name you might need to be a bit more careful, but this should get you a reasonable way.

这篇关于如何将一种类型的表达式树转换为不同的表达式类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆