在应用程序中编译 C# 代码 [英] Compile C# Code In The Application
问题描述
我想要一些代码来编译我的 TextBox 中的代码(例如).我的意思是我想在运行程序后编译代码.我该怎么做?
I want some code that compiles the code that is in my TextBox (for example). What I mean is I want to compile code after running the program. How can I do this?
推荐答案
查看这篇文章:
http://support.microsoft.com/kb/304655
这是他们提供的示例代码:
Here's the sample code they provide:
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
中结束,否则您将遇到内存泄漏.
As Aliostad has mentioned in his answer, be careful with this solution, though. You will need to make sure your compiled code ends up in its own AppDomain
, otherwise you will experience memory leaks.
请参阅有关如何将代码加载到单独的 AppDomain
中的相关问题:
See this related question on how to load the code into a separate AppDomain
:
如何防止 CompileAssemblyFromSource 泄漏内存?
这篇关于在应用程序中编译 C# 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!