你不必使用csi.exe,你可以在你的应用程序中实际编译和执行C# (与解决方案对象,类和方法的上下文相关)。
我还没有找到一些关于它的一些真实文档,旁边有一些blog posts。
你应该看看的主要方法是Microsoft.CodeAnalysis.CSharp.Scripting
和Microsoft.CodeAnalysis.Scripting
。
查看CSharpScript.RunAsync
和CSharpScript.EvaluteAsync
,这两者将编译并执行给定的C#脚本,其语法类似于csi.exe语法。
例如,如果你希望用户输入一些代码,并希望这个代码返回一些字符串,同时暴露用户的MyClass
组件:
private async void CompileAndExecuteLine(string userCode)
{
string output = "";
ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(typeof(MyClass).Assembly);
try
{
output = await CSharpScript.EvaluateAsync<string>(userCode, scriptOptions);
}
catch (CompilationErrorException cee)
{
string message = "You got errors:" + "\r\n";
foreach (Diagnostic dia in cee.Diagnostics)
{
message += dia.ToString() + "\r\n";
}
MessageBox.Show(message, "Compilation Error");
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return output;
}
在这个例子中,你进入必须返回一个字符串代码(需要以return someString;
结束),你可以调用引用程序集中的任何类和方法,甚至可以在userCode
(但不包含名称空间)中声明自己的类。
如果您希望有一些终端环境(=总是返回一些字符串),请考虑在执行之前操作用户定义的代码。
我假设您想要将您的游戏引擎的至少一些功能暴露给C#脚本? – zneak
@zneak是的。这是我能想到的唯一例子。 – johnny
我对这个问题不够了解,无法发布完整的解决方案,但是您可能希望查看'Microsoft.CSharp.CSharpCodeProvider'的方向。 – zneak