.NET - 将语句 lambda 主体转储到字符串
给出以下语句 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以那种形式是不可能的。你的 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 justAction
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.
阅读此处的教程,
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.