我想要一些代码来编译我的 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
的相关问题:
How can I prevent CompileAssemblyFromSource from leaking memory?
关于c# - 在应用程序中编译 C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7944036/