簡體   English   中英

在應用程序中編譯C#代碼

[英]Compile C# Code In The Application

我想要一些代碼來編譯我的TextBox中的代碼(例如)。 我的意思是我想在運行程序后編譯代碼。 我怎樣才能做到這一點?

看到這篇文章:

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請參閱此相關問題:

如何防止CompileAssemblyFromSource泄漏內存?

看到這里這里

請注意 ,任何編譯和加載的代碼都無法卸載。 這可能會導致內存泄漏 ,即如果有人不斷輸入並更改代碼並進行編譯,程序集就會被加載,最終會耗盡內存。

一種解決方案是創建第二個AppDomain並在其中加載程序集,當不需要時,卸載AppDomain。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM