将表达式树转换为源代码字符串 [英] Convert an Expression Tree to Source Code string

查看:24
本文介绍了将表达式树转换为源代码字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下签名的函数...

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

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

我试图找到一种方法将表达式"参数转换回类似于原始源代码的内容(或至少是原始源代码的 c# 表示).所以,如果有人像这样调用函数......

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)

有人这样做过吗?

推荐答案

我刚刚遇到了这个问题;我编写了一个免费的开源库,它提供了一种扩展方法来从表达式创建类似源代码的字符串:

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();

我写了一篇关于它的博客,来源在 GitHub 上,还有 一个包含扩展方法的 NuGet 包,我为 VS 2010 编写了一组调试器可视化工具 ->2019 年位于 Visual Studio Marketplace.

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.

这篇关于将表达式树转换为源代码字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆