Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

.net - Convert an Expression Tree to Source Code string

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

public string DoJunk(Expression<Func<bool>> expression)

I'm trying to find a way to convert the "expression" parameter back to something resembling the original source code (or at least a c# representation of the original souce code). So, if someone calls the function like this...

DoJunk(() => (i + j) * 9 == Math.Round((double)j / (i - 3), 4))

...I'd like to be able to convert the expression to this...

(i + j) * 9 == Math.Round((double)j / (i - 3), 4)

Has anyone done this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...