1

I have build expression parser CreateExpression() which return constructed Expression Tree

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

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

So I print out expression 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(); 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?

ipoppo
  • 369
  • 2
  • 11

1 Answers1

4

Most likely your CreateExpression() does not reference parameters that are in _ParameterExpressions, but defines its own instead. You have to use same ParameterExpression in expression tree you're compiling and in lambda arguments.

Sergei Rogovtcev
  • 5,804
  • 2
  • 22
  • 35