表达式树中的绑定参数

Spo*_*les 10 c# expression-trees c#-3.0

我想知道如何将参数绑定到表达式树中的值

就像是

Expression<Func<String, String, bool>> e1 = (x,y) => x == y;
Run Code Online (Sandbox Code Playgroud)

然后我想绑定y,同时保留它作为单个表达式.一个明显的尝试将是类似的

Expresion<Func<String, bool>> e2 = x => e1(x, "Fixed Value Here");
Run Code Online (Sandbox Code Playgroud)

但那会把我的表达变成一个Invoke节点.有没有办法在获取第二个表达式的签名时简单地绑定我的第一个表达式中的参数?

Mar*_*ell 18

Expression<Func<String, String, bool>> e1 = (x,y) => x == y;

var swap = new ExpressionSubstitute(e1.Parameters[1],
    Expression.Constant("Fixed Value Here"));
var lambda = Expression.Lambda<Func<string, bool>>(
    swap.Visit(e1.Body), e1.Parameters[0]);
Run Code Online (Sandbox Code Playgroud)

class ExpressionSubstitute : ExpressionVisitor
{
    public readonly Expression from, to;
    public ExpressionSubstitute(Expression from, Expression to)
    {
        this.from = from;
        this.to = to;
    }
    public override Expression Visit(Expression node)
    {
        if (node == from) return to;
        return base.Visit(node);
    }
}
Run Code Online (Sandbox Code Playgroud)

这用于ExpressionVisitor重建表达式,y用常量替换.

另一种方法是使用Expression.Invoke,但这并不适用于所有情况.