如何将一种类型的表达式树转换为另一种类型的表达式
本文关键字:类型 表达式 转换 另一种 一种 | 更新日期: 2023-09-27 18:02:02
如果我有两个几乎相同的类Animal
和AnimalViewModel
以及与视图模型相关的表达式树,我如何将其转换为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.
}
这里有一个访问者来完成这项工作。
- 它会复制该参数(因为我们需要创建一个新参数并将旧参数的所有引用替换为新参数)
- 遍历树的
.Body
,替换参数,并将对旧类型的任何成员访问切换到新类型 上的同名成员。 - 它使用我们之前发明的参数重新组装一个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
,你可能需要更小心一点,但这应该会让你得到一个合理的方式。
您尝试过Automapper做这样的事情吗?