简体   繁体   English

C#Expression.Lambda无法在运行时编译

[英]C# Expression.Lambda cannot be compiled at runtime

I have build expression parser CreateExpression() which return constructed Expression Tree 我有构建表达式解析器CreateExpression() ,它返回构造的表达式树

Expression rule = CreateExpression(_BuyRuleString);
LambdaExpression lambda = Expression.Lambda(rule, _ParameterExpressions);
var func = lambda.Compile();

but it failed when I call lambda.Compile() with the error 但是当我用lambda.Compile()调用错误时失败了

variable 't1' of type 'System.Int32' referenced from scope '', but it is not defined

So I print out expression lambda 所以我打印出表达式lambda

.Lambda #Lambda1<System.Func`9[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Double,System.Double,System.Boolean[]]>(
System.Int32 $t1,
System.Int32 $t2,
System.Int32 $t3,
System.Int32 $t4,
System.Int32 $t5,
System.Int32 $t6,
System.Double $r1,
System.Double $r2) {
.Call SwarmTrader.ExpressionParser.SeriesOperatorFunc.GTZ(.Call SwarmTrader.Indicator.RSI(
        $t1,
        "p"))
}

which equivalent to 相当于

Expression<Func<int, int, int, int, int, int, double, double, bool[]>> test = (t1, t2, t3, t4, t5, t6, r1, r2) => SwarmTrader.ExpressionParser.SeriesOperatorFunc.GTZ(SwarmTrader.Indicator.RSI(t1, "p"));

But var func = test.Compile(); var func = test.Compile(); works. 作品。 So I try resolve it in combination ... 所以我尝试组合解决它...

lambda = Expression.Lambda(rule, _ParameterExpressions); // lambda.Compile() failed
lambda = Expression.Lambda(test.Body, _ParameterExpressions); // lambda.Compile() failed
lambda = Expression.Lambda(rule, test.Parameters); // lambda.Compile() failed
lambda = Expression.Lambda(test.Body, test.Parameters); // lambda.Compile() works

Can anyone point out why lambda.Compile() does work only from test ? 任何人都可以指出为什么lambda.Compile()只能从test中起作用吗?

Most likely your CreateExpression() does not reference parameters that are in _ParameterExpressions , but defines its own instead. 很可能你的CreateExpression()不引用_ParameterExpressions参数,而是定义它自己的参数。 You have to use same ParameterExpression in expression tree you're compiling and in lambda arguments. 您必须在正在编译的表达式树和lambda参数中使用相同的 ParameterExpression

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM