加载程序集并更改源,是否可能以及如何实现?
我正在为 CLR 脚本编写 .NET On-the-Fly 编译器,并希望实现下一个想法:有一个包含 C# 代码的模板文件,我想读取它、创建程序集、加载它并即时放大源代码。 我怎样才能做到这一点?
I'm writing .NET On-the-Fly compiler for CLR scripting and want to implement next idea: there is a template file with C# code, I want to read it, create an assembly, load it and amplify source on-the-fly. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以使用 CompileAssemblyFromSource 来执行此操作。 我过去做过类似的事情,我用静态类包装器增强了一些脚本,以便可以轻松调用它们。 您可以在这里查看它(或从中窃取)。
为此,只需加载模板,将额外的放大添加到代码中,然后一次性编译即可。
如果要修改现有程序集,则需要使用类似 Mono.Cecil 的内容。 它允许您在运行时作为程序集加载和修改。 有一篇使用 Reflexil(基于 GPL 产品)的 CodeProject 文章关于塞西尔,这可能会帮助你得到一些想法......
You can do this with CompileAssemblyFromSource. I've done something simliar in the past, where I augmented some scripts with static class wrappers so they could easily be called. You can see it (or steal from it) here.
To do this, just load your template, add your extra amplifications to the code, and compile it in one shot.
If you want to modify an existing assembly, you will need to use something like Mono.Cecil. It allows you to load and modify as assembly at runtime. There is a CodeProject article using Reflexil, a GPL product based on Cecil, which may help you get some ideas...