LambdaExpression Variable Referenced From Scope Bu

2019-06-26 05:51发布

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条回答
三岁会撩人
2楼-- · 2019-06-26 06:00

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.

查看更多
登录 后发表回答