Lambda 到表达式树的转换

发布于 2024-08-02 07:33:13 字数 63 浏览 1 评论 0 原文

我会保持非常简单,

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

或者来自查询表达式?

I will keep it really simple,

How do I get expression tree out of lambda??

or from query expression ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

笑红尘 2024-08-09 07:33:13

您必须将 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;

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

You must assign the lambda to a different type:

// 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.

仲春光 2024-08-09 07:33:13

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

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

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.

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 Cecil library, which provides advanced IL manipulation support and could save you quite some time.

却一份温柔 2024-08-09 07:33:13

只是为了扩展 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);

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:

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

// Gives you an expression tree:
Expression<Func<int, int>> g = x => f(x);
来世叙缘 2024-08-09 07:33:13

运行时替代方案是使用此项目 - https://github.com/kostat/XLinq

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

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

A runtime alternative is to use this project - https://github.com/kostat/XLinq :

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

// Gives you an expression tree:
Expression<Func<int, int>> g = ExpressionTree.Parse(f);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文