Binding parameter in Expression trees

无人久伴 提交于 2019-12-04 11:17:26

问题


I would like to know how to bind parameters to values within an expression tree

Something like

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

Then I would like to bind y, while preserving it as a single expression. A obvious attempt would be something like

Expresion<Func<String, bool>> e2 = x => e1(x, "Fixed Value Here");

But that would turn my expression into an Invoke node. Is there a way to simply bind a parameter within my first expression while getting the signature of the second expression?


回答1:


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]);

with

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);
    }
}

this uses ExpressionVisitor to rebuild the expression, substituting y with the constant.

Another approach is to use Expression.Invoke, but this doesn't work in all cases.



来源:https://stackoverflow.com/questions/8610506/binding-parameter-in-expression-trees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!