从我的程序中运行其他C#代码

时间:2014-02-07 15:53:15

标签: c# debugging command-line execution

我正在尝试为我正在使用C#开发的游戏制作类似命令行的内容。 我希望有类似的东西:

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

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

2 个答案:

答案 0 :(得分:0)

您可以动态编译程序集

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

答案 1 :(得分:0)

看看project Roslyn。特别是Scripting document应该让你顺利。

代码太大而无法包含在这里。