从范围引用但未定义的 LambdaExpression 变量
我有一个简单的 lambda 表达式,我想编译和调用它,
Expression< Func< Commands, bool>> expression = c => c.IsValid("test");
但是当我执行以下操作时:
LambdaExpression le = Expression.Lambda(expression.Body);
object result = le.Compile().DynamicInvoke();
编译会抛出错误:
从范围“”引用了“ConsoleApplication1.Commands”类型的变量“c”,但未定义
如何为此表达式设置实例变量?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不直接编译表达式本身呢?如果您想使用某些特定的“ConsoleApplication1.Commands”实例多次调用它,则可以关闭该实例:
否则您将需要构建调用表达式,如下所示:
或者您可以创建 ExpressionVisitor 它将替换所有“expression.Body”中“c”参数与 Expression.Constant 一起出现。
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:
Otherwise you'll need to build call expression, like this:
or you can make ExpressionVisitor which will replace all occurences of the 'c' parameter in 'expression.Body' with Expression.Constant.