【问题标题】:C# Expression.Lambda cannot be compiled at runtimeC# Expression.Lambda 无法在运行时编译
【发布时间】:2012-09-01 17:53:52
【问题描述】:

我已经构建了表达式解析器CreateExpression(),它返回构造的表达式树

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

但是当我调用 lambda.Compile() 时它失败了

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

所以我打印出表达式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"))
}

相当于

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

但是var func = test.Compile(); 有效。所以我尝试结合解决它...

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

谁能指出为什么lambda.Compile() 只能从test 工作?

【问题讨论】:

  • 你能显示规则和_ParameterExpressions中的内容吗?

标签: c# expression-trees


【解决方案1】:

很可能您的CreateExpression() 没有引用_ParameterExpressions 中的参数,而是定义了自己的参数。您必须在您正在编译的表达式树和 lambda 参数中使用 same ParameterExpression

【讨论】:

  • 所以它不是通过参数名称引用而是ParameterExpression的实例?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多