Binding parameter in Expression trees

前端 未结 1 696
一整个雨季
一整个雨季 2021-02-08 11:30

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

Something like

Expression

        
1条回答
  •  情歌与酒
    2021-02-08 12:01

    Expression> e1 = (x,y) => x == y;
    
    var swap = new ExpressionSubstitute(e1.Parameters[1],
        Expression.Constant("Fixed Value Here"));
    var lambda = Expression.Lambda>(
        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.

    0 讨论(0)
提交回复
热议问题