将方法转换为 C# 源代码
我正在编写一个相当简单的代码生成工具,并且我需要能够将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个 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.
我作为应用程序的一部分编写的代码生成器使用
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 withString.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?