.NET - dump lambda body command for string

Given the following example of a lambda expression:

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

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

thanks

+7
source share
3 answers

In this form, this is not possible. Your lamda is compiled into bytecode. Although it is theoretically possible to decompile the bytecode, just like a reflector, it is difficult, error prone and does not give you the exact code that you compiled, but simply the code equivalent.

If you use Expression<Action> instead of a simple Action , you will get an expression tree that describes lamda. And it is possible to convert the expression tree to a string (and there are existing libraries that do this).

But this is not possible in your example, because it is a verbose lamda instruction. And only simple lams can be automatically converted to an expression tree.

+11
source

Read 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 that he uses to traverse this expression tree. You should be able to change it to suit your needs quite easily.

0
source

All Articles