如何将一种类型的表达式树转换为不同的表达式类型?

时间:2011-07-14 19:02:18

标签: c# c#-4.0 lambda expression-trees

如果我有两个几乎相同的类AnimalAnimalViewModel以及与viewmodel相关的表达式树,我该如何将其翻译为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<Func<AnimalViewModel,bool>>翻译为Expression<Func<Animal,bool>>

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

2 个答案:

答案 0 :(得分:8)

这是一位完成这项工作的访客。

  • 它制作参数的副本(因为我们需要创建一个新参数并替换旧参数的所有引用)
  • 它遍历树的.Body,替换参数,并将类型的任何成员访问权转换为 new上的同名成员 type
  • 使用我们发明的参数earler
  • 重新组装一个lambda

代码:

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,你可能需要更加小心,但这应该让你有一个合理的方法。

答案 1 :(得分:0)

你有没有尝试Automapper这样的事情?