使用LINQ表达式时,C#编译器可以方便地将C#lambdas转换为Expression对象:
//using System;
//using System.Linq.Expressions;
Expression<Func<int, bool>> lambda_expression = (int x) => x == 3;
这很方便,与明确构建表达式相比可以节省大量的输入:
Expression<Func<int, bool>> explicit_expression_object;
{
var x = Expression.Parameter(typeof(int), "x");
explicit_expression =
Expression.Lambda<Func<int, bool>>(Expression.Equal(x, Expression.Constant(3)), x);
}
但是,有些情况下需要使用“longhand”Expression对象语法,例如在运行时动态创建表达式时。因此,我目前发现自己使用了“表达式lambdas”和动态生成的“显式”表达式对象。
是否可以将Expression对象“包含”或“嵌入”到表达式lambda?
中例如:
Expression inner_expression_object = Expression.Constant(3);
Expression<Func<int, bool>> wrapper_expression =
(int x) => x == inner_expression_object.Embed();
答案 0 :(得分:3)
使用ExpressionVisitor
,您可以使用Expression
替换对Expression
扩展方法的调用。
首先,您需要一个ExpressionVisitor
类来将Embed
方法调用扩展为其值:
public class EmbedVisitor : ExpressionVisitor {
public override Expression Visit(Expression node) {
if (node?.NodeType == ExpressionType.Call) {
var callnode = node as MethodCallExpression;
if (callnode.Method.Name == "Embed" && callnode.Method.DeclaringType == typeof(ExpressionExt))
return callnode.Arguments[0].Evaluate<Expression>();
}
return base.Visit(node);
}
}
然后你需要一个静态类来获得所需的扩展方法:
public static class ExpressionExt {
public static T Embed<T>(this Expression e) {
return default(T);
}
public static Expression ExpandEmbed(this Expression orig) => new EmbedVisitor().Visit(orig);
public static T Evaluate<T>(this Expression e) {
//A little optimization for constant expressions
if (e.NodeType == ExpressionType.Constant)
return (T)((ConstantExpression)e).Value;
else
return (T)Expression.Lambda(e).Compile().DynamicInvoke();
}
}
现在您可以使用它们来扩展嵌入的Expression
值子表达式:
var inner_expression_object = Expression.Constant(3);
Expression<Func<int, bool>> wrapper_expression =
(int x) => x == inner_expression_object.Embed<int>();
var expanded = wrapper_expression.ExpandEmbed();
// Expression<Func<int,bool>> expanded == (int x) => x == 3;
您还可以直接嵌入Expression
表达式并展开它们:
Expression<Func<int,bool>> wrap2 = x => x == Expression.Multiply(Expression.Constant(4), Expression.Constant(8)).Embed<int>();
var expanded2 = wrap2.ExpandEmbed();
// Expression<Func<int,bool>> expanded2 = x => x == 4*8;