Variable LambdaExpression Scope Referenced But Not Defined

c# expression-trees

Question

I want to build and call a straightforward lambda expression.

Expression< Func< Commands, bool>> expression = c => c.IsValid("test");

but if I carry out the following:

LambdaExpression le = Expression.Lambda(expression.Body);

object result = le.Compile().DynamicInvoke();

During compilation, an error is thrown:

variable 'c' of type 'ConsoleApplication1.Commands' referenced from scope '', but it is not defined

How do you set this expression's instance variable?

1
4
10/12/2011 7:55:01 AM

Popular Answer

Why not compile the expression directly instead? You could just shut over that instance if you wanted to repeatedly execute it with a particular "ConsoleApplication1.Commands" instance:


var validator = expression.Compile();

var c = new Commands();
var validatorForC = () => validator(c);

If not, you must construct a call expression like this:


var c = new Commands();
var le = Expression.Lambda(Expression.Invoke(expression, Expression.Constant(c)));
object result = le.Compile().DynamicInvoke();

instead you can create an ExpressionVisitor that will substitute Expression for every instance of the 'c' argument in the 'expression.Body'. Constant.

4
10/12/2011 7:47:11 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow