在应用程序中编译C#代码

时间:2011-10-30 08:53:15

标签: c# c#-4.0 compilation

我想要一些代码来编译我的TextBox中的代码(例如)。我的意思是我想在运行程序后编译代码。我怎么能这样做?

2 个答案:

答案 0 :(得分:21)

参见这篇文章:

http://support.microsoft.com/kb/304655

以下是他们提供的示例代码:

var codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();

var parameters = new CompilerParameters()
{
    GenerateExecutable = true,
    OutputAssembly = Output,
};
CompilerResults results = icc.CompileAssemblyFromSource(parameters, sourceString);

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

正如Aliostad在回答中提到的那样,要小心这个解决方案。您需要确保已编译的代码最终位于其自己的AppDomain中,否则您将遇到内存泄漏。

请参阅此相关问题,了解如何将代码加载到单独的AppDomain

How can I prevent CompileAssemblyFromSource from leaking memory?

答案 1 :(得分:17)

请参阅herehere

小心,无法卸载任何编译和加载的代码。这可能会导致内存泄漏,即如果有人不断输入并更改代码并进行编译,程序集就会被加载,最终会耗尽内存。

一种解决方案是创建第二个AppDomain 并在其中加载程序集,在不需要时卸载AppDomain。

相关问题