【问题标题】:Compile code in a textbox and save to exe在文本框中编译代码并保存到 exe
【发布时间】:2012-04-16 16:17:27
【问题描述】:

是否可以在文本框中编译任何给定的 C# 代码,然后将其保存到 exe 中?

这可能吗?如果可以,怎么做?

【问题讨论】:

  • 您自己是否对这个主题进行过任何研究?如果有,你发现了什么?
  • 是的,我发现只是运行时编译,但没有保存。
  • Stack Overflow 对那些只是提出问题而没有表现出任何努力自己解决的问题会皱眉头。我会编辑您的问题以包含指向您找到的在线资源的链接,并提出具体问题,而不仅仅是“有可能吗?”

标签: c# compiler-construction compilation exe


【解决方案1】:

是的,这是可能的。你可以使用CodeDOM。这是an example

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Rnge(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

【讨论】:

    【解决方案2】:

    除了在运行时编译代码,您可以将文本框中的代码保存到磁盘,然后使用csc.exe 进行编译。该命令类似于以下内容:

    %systemroot%\Microsoft.NET\Framework\v3.5\csc /out:filename.exe filename.cs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多