c# - 我可以使用 Reflection.Emit 生成代码并将生成的代码保存在 .cs 文件中,还是可以使用 CodeDom?

标签 c# code-generation runtime reflection.emit codedom

我想写一个代码生成器并用 mvp 模式保存这些代码,我可以使用 Reflection.Emit 作为解决方案还是 CodeDom 更好?

编辑----------------

我必须做 2 项工作,首先我想在运行时编译此代码并运行它,其次生成源代码作为选项。

最佳答案

尽管您可以使用两个命名空间(System.CodeDomSystem.Reflection.Emit)来解决问题的某些方面,但您不能混合使用这两个不同的概念,并且使用更适合您想做的事情的选项。

如果您只想生成和编译 C#\VB 代码,也许您想要使用 System.CodeDom:

This namespace can be used to model the structure of a source code document that can be output as source code in a supported language using the functionality provided by the System.CodeDom.Compiler namespace.

查看这个关于如何通过 CodeDom 定义方法的小示例:

// Defines a method that returns a string passed to it.
CodeMemberMethod method1 = new CodeMemberMethod();            
method1.Name = "ReturnString";
method1.ReturnType = new CodeTypeReference("System.String");
method1.Parameters.Add( new CodeParameterDeclarationExpression("System.String", "text") );
method1.Statements.Add( new CodeMethodReturnStatement( new CodeArgumentReferenceExpression("text") ) );            

// A C# code generator produces the following source code for the preceeding example code:

//    private string ReturnString(string text) 
//    {
//        return text;
//    }

至于 System.Reflection.Emit,它用于生成和操作 MSIL(Microsoft 中间语言),这是由.NET Framework 使用的公共(public)语言基础结构规范。请注意,MSIL 现在称为 CIL(通用中间语言):

The System.Reflection.Emit namespace contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) and optionally generate a PE file on disk. The primary clients of these classes are script engines and compilers.

使用这种方法会引导您学习 CIL 字节码指令,即使您熟悉汇编代码,这也是一项相当困难和复杂的任务,如果您想要的实现起来相当简单和快速,则可能不是理想的选择。查看有关 CIL 的维基百科文章和 CIL instructions list第一印象。

关于c# - 我可以使用 Reflection.Emit 生成代码并将生成的代码保存在 .cs 文件中,还是可以使用 CodeDom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6501224/

相关文章:

c# - ODP.NET 错误无法找到请求的 .Net Framework 数据提供程序

Java 全局命名空间访问

python - 我可以通过编译来提高 python 运行时吗?

c++ - C++:检测 vector 在函数中是否为<complex>类型

c# - Visual Studios 2015 中的 "Restore NuGet Packages"未执行任何操作

c# - Entity Framework 连接字符串

c# - 在 Windows 窗体中为 Font 调用 dispose()

haskell - 类型检查生成的代码访问 Haskell 中动态加载的代码

c - 如何使用 cmake 生成包含文件?

java - 从Java执行C时出现奇怪的错误