如何利用C#编程对一段程序进行编译?

C#提供了在程序中对一段代码进行动态编译的机制。可以在一个文本框内输入代码,然后利用本文的技术进行编译,然后生成可执行代码。

//指定生成的可执行文件名
string Output="xyz.exe"

//源程序
string SourceString;

//codeProvider是进行编译的类
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();

//设置编译参数
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;

//编译源程序
CompilerResults results = icc.CompileAssemblyFromSource(parameters,SourceString);

//输出错误
if (results.Errors.Count > 0)
{
  foreach(CompilerError CompErr in results.Errors)
  {
    textBox2.Text = textBox2.Text +
    "Line number " + CompErr.Line +
    ", Error Number: " + CompErr.ErrorNumber +
    ", '" + CompErr.ErrorText + ";" +
    Environment.NewLine + Environment.NewLine;
  }
}

//执行得到的可执行文件
Process.Start(Output);