将方法转换为 C# 源代码

发布于 2024-07-16 10:46:19 字数 333 浏览 3 评论 0原文

我正在编写一个相当简单的代码生成工具,并且我需要能够将 MSIL(或 MethodInfo)对象转换为其 C# 源代码。 我意识到 Reflector 在这方面做得很好,但它有一个令人讨厌的“功能”:仅是 UI。

我知道我可以直接生成 C# 字符串,使用 string.Format 插入变量部分,但我真的更喜欢能够以编程方式生成方法(例如委托或 MethodInfo 对象),然后将这些方法传递给编写器这会将它们转换为 C#。

系统库使得在运行时从 C# 源代码字符串转换为编译(可执行)方法变得如此容易,但不可能从对象转换为源代码——即使是简单的事情,这似乎有点愚蠢。

有任何想法吗?

I am writing a fairly simple code gen tool, and I need the ability to convert MSIL (or MethodInfo) objects to their C# source. I realize Reflector does a great job of this, but it has the obnoxious "feature" of being UI only.

I know I could just generate the C# strings directly, using string.Format to insert the variable portions, but I'd really prefer to be able to generate methods programatically (e.g. a delegate or MethodInfo object), then pass those methods to a writer which would convert them to C#.

It seems a little silly that the System libraries make it so easy to go from a C# source code string to a compiled (and executable) method at runtime, but impossible to go from an object to source code--even for simple things.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木槿暧夏七纪年 2024-07-23 10:46:19

这个 Reflector 插件可让您输出到文件,并且可以从以下位置运行 Reflector:命令行。 让它做你想做的事情可能比推出你自己的反编译器更简单。

Anakrino 是另一个带有命令行选项的反编译器,但自 以来就没有更新过。 NET 1.1。 不过,它是开源的,因此您可以将您的解决方案基于它。

This add-in for Reflector lets you output to a file, and it is possible to run Reflector from the command line. It's probably simpler to get that to do what you want than to roll your own decompiler.

Anakrino is another decompiler with a command line option, but it hasn't been updated since .NET 1.1. It's open source, though, so you might be able to base your solution on it.

靖瑶 2024-07-23 10:46:19

我作为应用程序的一部分编写的代码生成器使用 String.Format,尽管我对 String.Format 并不完全满意(Lisp 宏在任何时候都击败了它)天)它的工作做得很好。 无论如何,C# 编译器都会重新检查所有生成的方法,因此通过 Reflection.Emit 和(尚未编写的)MSIL 到 C# 反编译器进行往返,您将一无所获。

PS:如果你想使用重量级的东西,为什么不使用CodeDOM呢?

The code generators which I wrote as part of our application use String.Format, and although I am not entirely happy with String.Format (Lisp macros beat it any time of the day) it does the job all right. The C# compiler is going to re-check all your generated methods anyway, so you gain nothing by round-tripping through Reflection.Emit and the (still unwritten) MSIL-to-C# decompiler.

PS: why not use CodeDOM if you want to use something heavyweight?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文