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

时间:2009-03-02 23:30:12

标签: c# .net dll code-generation

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

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

3 个答案:

答案 0 :(得分: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);

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

答案 1 :(得分:31)

非弃用的方式(使用.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));
    }
}

答案 2 :(得分:4)

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