.NET - DUMP语句的lambda体字符串字符串、语句、NET、DUMP

2023-09-04 22:42:36 作者:海绵丢了宝宝

由于以下语句的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.

 
精彩推荐
图片推荐