LambdaExpression变量引用从范围但没有定义 [英] LambdaExpression Variable Referenced From Scope But Not Defined

查看:208
本文介绍了LambdaExpression变量引用从范围但没有定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的lambda表达式,我想编译并调用

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:

型的'ConsoleApplication1.Commands距离范围'引用,但它没有定义

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

如何设置,该表达式的实例变量?

How do you set the instance variable for this expression?

推荐答案

为什么不直接编译表达式本身呢?如果您想与一些特定的ConsoleApplication1.Commands实例来调用它多次,然后你可以正好接近了该实例:

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();



也可以使ExpressionVisitor将取代C参数的所有出现在expression.Body与Expression.Constant。

or you can make ExpressionVisitor which will replace all occurences of the 'c' parameter in 'expression.Body' with Expression.Constant.

这篇关于LambdaExpression变量引用从范围但没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆