.NET - DUMP语句的lambda体字符串 [英] .NET - dump statement lambda body to string

查看:171
本文介绍了.NET - DUMP语句的lambda体字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下语句的lambda例如:

Given the following statement lambda example:

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

什么是可能的方式来获取的lambda的机构,它转储到字符串? (有什么,这将最终允许写动作类这种扩展方法: fMyAction.Dump()这将返回X + = 2;东西=什么+,直到永远。

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;").

感谢

推荐答案

这是不可能的这种形式。你LAMDA被编译成字节级code。虽然在理论上是可能的反编译的字节级code,就像反射器是不,这是困难的,容易出错,不给你确切的code您编译,而只是code这是等价的。

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.

如果您使用的是防爆pression<作用> ,而不是仅仅动作你得到的前pression树描述LAMDA。而将一个前pression树为一个字符串是可能的(并且有哪些做现有的库)。

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

但是,这不可能在你的榜样,因为它是一个多语句LAMDA。而且,只有简单的lamdas可以自动转换到前pression树。

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.

这篇关于.NET - DUMP语句的lambda体字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆