C# 在运行时动态生成 DLL 程序集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/604501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:01:37  来源:igfitidea点击:

Generating DLL assembly dynamically at run time

c#.netdllcode-generation

提问by 7wp

Currently I have some code that is being generated dynamically. In other words, a C# .cs file is created dynamically by the program, and the intention is to include this C# file in another project.

目前我有一些动态生成的代码。换句话说,程序动态创建了一个 C# .cs 文件,目的是将这个 C# 文件包含在另一个项目中。

The challenge is that I would like to generate a .DLL file instead of generating a C# .cs file so that it could be referenced by any kind of .NET application (not only C#) and therefore be more useful.

挑战在于我想生成一个 .DLL 文件而不是生成一个 C# .cs 文件,以便它可以被任何类型的 .NET 应用程序(不仅仅是 C#)引用,因此更有用。

采纳答案by Rex M

using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;

CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = "AutoGen.dll";
CompilerResults results = icc.CompileAssemblyFromSource(parameters, yourCodeAsString);

Adapted from http://support.microsoft.com/kb/304655

改编自http://support.microsoft.com/kb/304655

回答by Marc Gravell

Right now, your best bet is CSharpCodeProvider; the plans for 4.0 include "compiler as a service", which will make this fully managed.

现在,你最好的选择是CSharpCodeProvider;4.0 的计划包括“编译器即服务”,这将使其得到全面管理。

回答by Anssssss

The non-deprecated way of doing it (using .NET 4.0 as previous posters mentioned):

不推荐使用的方法(使用 .NET 4.0 作为前面提到的海报):

using System.CodeDom.Compiler;
using System.Reflection;
using System;
public class J
{
    public static void Main()
    {       
        System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateExecutable = false;
        parameters.OutputAssembly = "AutoGen.dll";

        CompilerResults r = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, "public class B {public static int k=7;}");

        //verify generation
        Console.WriteLine(Assembly.LoadFrom("AutoGen.dll").GetType("B").GetField("k").GetValue(null));
    }
}