Java中的嵌入式脚本,有Groovy(参考https://www.w3cschool.cn/groovy/),简单方便,最近想测试一下C#中类似的实现,找到了Roslyn,入手简单,和原生的C#一样强大。本文尝试用Demo实现脚本和本体进程之间使用API进行数据交换,写了一个简单的示例如下:
Program.cs示例代码段
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
var globals = new DynamicScript.DataMgr();
//此处是构建保持上下文状态的脚本
var state = await CSharpScript.RunAsync("", globals: globals);
do
{
Console.Write("请输入表达式:");
var command = Console.ReadLine();
if (command == "exit") break;
try
{
state = await state.ContinueWithAsync(command);
Console.WriteLine("ReturnValue:" + state.ReturnValue);
}
catch (CompilationErrorException e)
{
Console.WriteLine(string.Join(Environment.NewLine, e.Diagnostics));
}
} while (true);
DataMgr.cs代码段
namespace DynamicScript
{
public class DataMgr
{
Dictionary<string, Object> dict = new Dictionary<string, Object>();
public Object GetValue(string key)
{
if (dict.TryGetValue(key, out object val))
{
return val;
}
return null;
}
public void SetValue(string key, Object val)
{
dict[key] = val;
}
}
}
运行测试,输入如下语句验证:
SetValue("abc",100);return GetValue("abc");
int y = (int)GetValue("abc"); y = y*3; return y;
System.Console.WriteLine($"y={y}");
return 0;
return System.Math.Sqrt(y);
运行结果:
![](https://img-blog.csdnimg.cn/img_convert/4cb92d9d59e939993e2e07b0ac27ce43.png)
参考资料:
the-shining-new-csharp-scripting-api