1

我已经构建了表达式解析器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

4

1 回答 1

4

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

于 2012-09-01T18:03:43.883 回答