string code = @"
using System;
namespace First
{
public class Program
{
public static void Main()
{
" +
"Console.WriteLine(\"Hello, world!\");"
+ @"
}
}
}
";
//Create the provider and parameters of the compiler:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
/ *定义编译器的参数(可选)–至此,我们可以添加对外部库的引用。我们还可以定义是仅在内存中还是在DLL或EXE文件中生成编译后的代码:* /
// Reference to System.Drawing library
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
// True - memory generation, false - external file generation
parameters.GenerateInMemory = true;
// True - exe file generation, false - dll file generation
parameters.GenerateExecutable = true;
Compile assembly:
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
代码:https://www.codeproject.com/Tips/715891/%2FTips%2F715891%2FCompiling-Csharp-Code-at-Runtime
谢谢