Convert an Expression Tree to Source Code string

前端 未结 2 755
鱼传尺愫
鱼传尺愫 2020-12-01 16:06

I have a function that has the following signature...

public string DoJunk(Expression> expression)

I\'m trying to fi

相关标签:
2条回答
  • 2020-12-01 16:43

    Here's an interesting article, with code, discussing the conversion of expression trees back into something that resembles (roughly) the original source:

    Expression Trees-Lambdas to CodeDom Conversion

    As a side-note, have you tried calling the expression's ToString method?

    Expression<Func<int, int, bool>> expr =
        (i, j) => (i + j) * 9 == Math.Round((double)j / (i - 3), 4);
    
    Console.WriteLine(expr.ToString());
    // (i, j) => (Convert(((i + j) * 9)) = Round((Convert(j) / Convert((i - 3))), 4))
    
    Console.WriteLine(expr.Body.ToString());
    // (Convert(((i + j) * 9)) = Round((Convert(j) / Convert((i - 3))), 4))
    
    0 讨论(0)
  • 2020-12-01 16:58

    I've just happened across this; I've written a free, open-source library which provides an extension method to create a source-code-like string from an Expression:

    using AgileObjects.ReadableExpressions;
    
    var myExpression = CreateBigExpressionTree();
    var expressionSource = myExpression.ToReadableString();
    

    I've written a blog about it, the source is on GitHub, there's a NuGet package containing the extension method, and I've written a set of Debugger Visualizers for VS 2010 -> 2019 which are in the Visual Studio Marketplace.

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