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

7wp*_*7wp 31 .net c# dll code-generation

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

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

Rex*_*x M 39

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);
Run Code Online (Sandbox Code Playgroud)

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


Ans*_*sss 32

这种非弃用的方式(使用.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));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你使用`parameters.GenerateInMemory = true;`,你可以使用`r.CompiledAssembly`获得内存中的程序集 (2认同)

Mar*_*ell 5

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