C# Roslyn编写脚本数据交互示例

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 dict = new Dictionary();
        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);

运行结果:

C# Roslyn编写脚本数据交互示例_第1张图片

参考资料:

https://gsferreira.com/archive/2016/02/the-shining-new-csharp-scripting-api/

https://www.cnblogs.com/dongweian/p/15773934.html

https://www.cnblogs.com/podolski/p/14192599.html

你可能感兴趣的:(编程,c#,Roslyn,脚本引擎)