在运行时dynamic生成DLL程序集

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

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

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

这样做的不推荐的方式(使用.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)); } } 

现在,你最好的select是CSharpCodeProvider ; 4.0的计划包括“编译器即服务”,这将使其得到充分的pipe理。