LambdaExpression Variable Referenced From Scope But Not Defined

∥☆過路亽.° 提交于 2019-12-10 16:17:03

问题


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

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