C# Lambda 到表达式树的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1310752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:59:00  来源:igfitidea点击:

Lambda to Expression tree conversion

c#lambdaexpression-trees

提问by Prashant Cholachagudda

I will keep it really simple,

我会保持非常简单,

How do I get expression tree out of lambda??

如何从 lambda 中获取表达式树?

or from query expression ?

还是来自查询表达式?

采纳答案by Konrad Rudolph

You must assign the lambda to a different type:

您必须将 lambda 分配给不同的类型:

// Gives you a delegate:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => x * 2;

The same goes for method arguments. However, once you've assigned such a lambda expression to a Func<>type, you can't get the expression tree back.

方法参数也是如此。但是,一旦将这样的 lambda 表达式分配给Func<>类型,就无法取回表达式树。

回答by Pierre Arnaud

Konrad's reply is exact. You need to assign the lambda expression to Expression<Func<...>>in order for the compiler to generate the expression tree. If you get a lambda as a Func<...>, Action<...>or other delegate type, all you have is a bunch of IL instructions.

康拉德的回答是准确的。您需要将 lambda 表达式分配给以Expression<Func<...>>让编译器生成表达式树。如果你得到一个lambda作为Func<...>Action<...>或其他委托类型,你已经是一堆的IL指令。

If you really need to be able to convert an IL-compiled lambda back into an expression tree, you'd have to decompile it (e.g. do what Lutz Roeder's Reflector tool does). I'd suggest having a look at the Cecillibrary, which provides advanced IL manipulation support and could save you quite some time.

如果您确实需要能够将 IL 编译的 lambda 转换回表达式树,则必须对其进行反编译(例如,执行 Lutz Roeder 的 Reflector 工具所做的工作)。我建议看看Cecil库,它提供了高级 IL 操作支持,可以为您节省相当多的时间。

回答by joniba

Just to expand on Konrad's answer, and to correct Pierre, you can still generate an Expression from an IL-compiled lambda, though it's not terribly elegant. Augmenting Konrad's example:

只是为了扩展 Konrad 的答案并纠正 Pierre,您仍然可以从 IL 编译的 lambda 生成表达式,尽管它不是非常优雅。增强康拉德的例子:

// Gives you a lambda:
Func<int, int> f = x => x * 2;

// Gives you an expression tree:
Expression<Func<int, int>> g = x => f(x);