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?

1
  • Could you show what is in rule and _ParameterExpressions? Commented Sep 1, 2012 at 17:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So it does not reference by parameter name but instance of ParameterExpression?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.