问题
I have a simple lambda expression that I would like to compile and invoke
Expression< Func< Commands, bool>> expression = c => c.IsValid("test");
but when I do the following:
LambdaExpression le = Expression.Lambda(expression.Body);
object result = le.Compile().DynamicInvoke();
the compile throws the error:
variable 'c' of type 'ConsoleApplication1.Commands' referenced from scope '', but it is not defined
How do you set the instance variable for this expression?
回答1:
Why not just compile the expression itself? If you'd like to invoke it with some specific 'ConsoleApplication1.Commands' instance multiple times you could then just close over that instance:
var validator = expression.Compile();
var c = new Commands();
var validatorForC = () => validator(c);
Otherwise you'll need to build call expression, like this:
var c = new Commands();
var le = Expression.Lambda(Expression.Invoke(expression, Expression.Constant(c)));
object result = le.Compile().DynamicInvoke();
or you can make ExpressionVisitor which will replace all occurences of the 'c' parameter in 'expression.Body' with Expression.Constant.
来源:https://stackoverflow.com/questions/7732770/lambdaexpression-variable-referenced-from-scope-but-not-defined