2014-02-07 40 views
0

我正在嘗試爲使用C#開發的遊戲製作類似於命令行的東西。 我想有這樣的:從我的程序中運行其他C#代碼

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

我在哪裏可以輸入與事發生在當前執行的線程在我的程序進行交互的C#代碼段(例如,如果我被困在一個無限循環在主程序中,我可以在單獨的線程中拉出命令行並輸入「break;」或「MainThread.Abort();」,然後我就可以出去了)。我希望能夠在運行時使用C#命令行與我的程序進行交互。我不知道這是否可能,但我認爲它會真正幫助我進行調試,例如使用命令行讓我的程序的一部分發生錯誤,並查看它如何處理它,而不必停止該程序,將錯誤添加到源代碼中,並重新構建)。 預先感謝您。

+0

你能舉出代碼變量內容的例子嗎? – Krzysztof

+2

你可以看看http://stackoverflow.com/questions/7944036/compile-c-sharp-code-in-the-application –

+0

C#代碼是[編譯語言](http://en.wikipedia。組織/維基/ Compiled_language)。它不能只是運行,就像javascript [解釋語言](http://en.wikipedia.org/wiki/Interpreted_language)。所以你需要編譯成可運行的東西,然後才能讓它做任何事情 – Liam

回答

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

+0

您對提供的解決方案有任何想法嗎? –