Expression/Statement trees

前端 未结 3 575
别那么骄傲
别那么骄傲 2021-02-13 22:34

Updated Question Further Down

I\'ve been experimenting with expression trees in .NET 4 to generate code at runtime and I\'ve been trying to implement th

相关标签:
3条回答
  • 2021-02-13 22:59

    You problem is that you didn't pass parameters and variables to your block expression. You use them in the "inner" expressions, but the block expression knows nothing about them. Basically, all you need to do is to pass all your parameters and variables to a block expression.

            var @foreach = Expression.Block(
                new ParameterExpression[] { item, enumerator, param },
                assignToEnum,
                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.NotEqual(doMoveNext, Expression.Constant(false)),
                        assignCurrent,
                        Expression.Break(@break))
                , @break)
            );
    
    0 讨论(0)
  • 2021-02-13 23:07

    Don't forget to dispose IEnumerator in try/finally - lots of code (such as File.ReadLines()) depends on that.

    0 讨论(0)
  • 2021-02-13 23:09

    Sorry if this is thread necromancy, but in case other people are running into the same or similar problem:

    You can try to write an ExpressionVisitor that replaces a parameter with the same name and type in the external body expression with the variable parameter you have declared when creating the block expression. That way the parameter in the body will be the same object as the parameter in the block declaration and so the LambdaExpression should compile.

    0 讨论(0)
提交回复
热议问题