.NET - dump statement lambda body to string

前端 未结 2 2071
情话喂你
情话喂你 2021-01-05 08:06

Given the following statement lambda example:

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

What ar

相关标签:
2条回答
  • 2021-01-05 08:38

    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.

    0 讨论(0)
  • 2021-01-05 08:53

    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.

    0 讨论(0)
提交回复
热议问题