.NET - 将语句 lambda 主体转储到字符串

发布于 2024-10-16 12:49:48 字数 295 浏览 0 评论 0原文

给出以下语句 lambda 示例:

var fMyAction = new Action(() =>
 {
    x += 2;
    something = what + ever; 
 });

获取该 lambda 主体并将其转储为字符串的可能方法有哪些? (最终允许为此类的 Action 类编写扩展方法:fMyAction.Dump() 它将返回 "x += 2; 某事=什么+曾经;”)。

谢谢

Given the following statement lambda example:

var fMyAction = new Action(() =>
 {
    x += 2;
    something = what + ever; 
 });

What are possible ways to get the body of that lambda and dump it to string? (Something that will ultimately allow to write an extension method for Action class of this kind: fMyAction.Dump() which will return "x += 2; something = what + ever;").

Thanks

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

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

发布评论

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

评论(2

叫思念不要吵 2024-10-23 12:49:48

以那种形式是不可能的。你的 lamda 被编译为字节码。虽然从理论上讲,可以像反射器一样反编译字节码,但它很困难,容易出错,并且不会为您提供编译后的确切代码,而只是等效的代码。

如果您使用Expression而不仅仅是Action你会得到描述 lamda 的表达式树。并且可以将表达式树转换为字符串(并且现有的库可以做到这一点)。

但这在您的示例中是不可能的,因为它是多语句 lamda。并且只有简单的 lamda 才能自动转换为表达式树。

It's not possible in that form. Your lamda gets compiled to byte-code. While in theory it's possible to decompile the byte-code, just like reflector does, it's difficult, error prone and doesn't give you the exact code you compiled, but just code that's equivalent.

If you use an Expression<Action> instead of just Action you get the expression tree describing the lamda. And converting an expression tree to a string is possible(and there are existing libraries which do it).

But that's not possible in your example because it's a multi statement lamda. And only simple lamdas can be automatically converted to an expression tree.

三五鸿雁 2024-10-23 12:49:48

阅读此处的教程,

http://blogs.msdn.com/b/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx

密切关注他用来遍历给定表达式树的访问者模式。您应该能够轻松地更改它以满足您的需求。

Read through the tutorial here,

http://blogs.msdn.com/b/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx

Pay close attention to the visitor pattern he uses to walk a given expression tree. You should be able to alter it to fit your needs easy enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文