Reverse of Expression>.Compile()?

后端 未结 4 1218
一个人的身影
一个人的身影 2020-12-11 17:06

Since we can:

Expression> predicate = x => x > 5;
var result = Enumerable.Range(0,10).Where(predicate.Compile());
         


        
4条回答
  •  清歌不尽
    2020-12-11 17:17

    Pass the lambda to a method that accepts an Expression<> and the C# compiler will pass you an expression tree at runtime. However this only works if you pass the lambda directly, not if you try to pass a delegate instance created from a lambda.

    var exp = Decompile(x => x > 5);
    
    public Expression> Decompile(Expression> exp)
    {
        return exp;
    }
    

    The closest option I've found for decompiling a delegate instance is detailed in this blog post from Jean-Baptiste Evain who works on the Mono team. He uses the excellent Mono.Cecil project to decompile the IL into a custom AST, then he maps it as best as possible into LINQ expressions.

提交回复
热议问题