【问题标题】:Running other C# code from inside my program [duplicate]从我的程序内部运行其他 C# 代码[重复]
【发布时间】:2014-02-07 15:53:15
【问题描述】:

我正在尝试为我正在使用 C# 开发的游戏制作类似命令行的东西。 我想要类似的东西:

string code;
code = Console.ReadLine();
Something.RunCode(code);

我可以在其中输入一个 C# 代码 sn-p,它与我的程序中当前执行线程发生的事情进行交互(例如,如果我在主程序中陷入无限循环,我可以拉出命令行在一个单独的线程中输入“break;”或“MainThread.Abort();”然后我就可以退出了)。我希望能够在程序运行时使用 C# 命令行与我的程序进行交互。我不知道这是否可能,但我认为它真的会帮助我进行调试等(比如使用命令行使我的程序的一部分抛出错误并查看它如何处理它,而不必停止程序,将错误添加到源代码中,然后重新构建)。 提前谢谢你。

【问题讨论】:

标签: c# debugging command-line execution


【解决方案1】:

您可以即时编译程序集

CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library";

compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;

compilerParams.OutputAssembly = outTempPath;

CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams, sourceCode);

出于安全原因,您应该对执行进行沙箱处理。

另外,请阅读this interesting article

【讨论】:

  • 您对所提供的解决方案有什么想法吗?
【解决方案2】:

看看project Roslyn。特别是Scripting document 应该让您上路。

代码太大了,这里就不放了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 2015-02-17
    • 1970-01-01
    相关资源
    最近更新 更多