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

标签 c# c#-4.0 compilation

我想要一些代码来编译我的 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/

相关文章:

c# - 有没有办法使用 WebClient 从受密码保护的位置而不是 Httprequest 获取登录 cookie?

c#-4.0 - c# - 将类传递给方法

c - ant target exec 失败,而在 shell 上运行命令成功

c - 如何在 C 中使用来自第三个 DLL 的两个 DLL 的代码?

c# - C 到 C# 字节数组 + 十六进制

c# - 如何找到违规列?无法从字符串转换为 int32

.net - 计算 ASP.net/c# 中的 session 数

c++ - 如何使用 cmake 添加不同的头文件夹,以便项目正确编译和运行

c# - 配置服务引用... - 对象引用未设置为对象的实例

c#-4.0 - 为什么在启动我的服务时会出现完成消息?