如何在 Roslyn 脚本环境中访问和编辑全局变量?

Sor*_*shi 0 c# scripting roslyn

我有一个应用程序,我在其中使用 Roslyn 脚本引擎(命名空间Microsoft.CodeAnalysis.Scripting)。

我现在所拥有的是:

public static async Task<object> Execute(string code, CommandEventArgs e)
{
    if (_scriptState == null)
    {
        var options = ScriptOptions.Default;
        options
            .AddReferences(typeof (Type).Assembly,
                typeof (Console).Assembly,
                typeof (IEnumerable<>).Assembly,
                typeof (IQueryable).Assembly)
            .AddImports("System", "System.Numerics", "System.Text", "System.Linq", "System.Collections.Generics",
                "System.Security.Cryptography");
        _scriptState = await CSharpScript.RunAsync(code, options, new MessageGlobal {e = e});
    }
    else
    {
        // TODO: set global e (it's not in this variables list, thus it throws null reference)
        _scriptState.GetVariable("e").Value = e;
        _scriptState = await _scriptState.ContinueWithAsync(code);
    }
    return !string.IsNullOrEmpty(_scriptState.ReturnValue?.ToString()) ? _scriptState.ReturnValue : null;
}
Run Code Online (Sandbox Code Playgroud)

更清楚地说:在我的应用程序中,有一个特定的事件。用户可以使用一些 C# 代码定义当事件发生时会发生什么(此代码经常更改)。现在的重点是 - 我需要将事件参数传递给脚本,以便用户可以在代码中使用它。同时,我需要保持引擎状态,因为用户可能已经定义了一些他想要下次使用的变量。

我已经可以传递事件 args(并像e在脚本中一样引用它),但只是第一次(即当它ScriptState为空并且我创建一个新的时)。下次运行此脚本或其他脚本 ( ScriptState.ContinueWithAsync) 时,事件参数与之前的状态相同,因为我不知道如何更新它们。

如何到达e全局并将其设置为新值?我已经尝试通过Variables列表访问它(如您在代码中所见),但似乎全局变量并未保留在列表中。同时我在运行第一个脚本时不能添加任何变量,因为ScriptVariable该类有一个内部构造函数。( ScriptState.Variables.Add( ScriptVariable ))

谢谢您的帮助。我希望我已经阐明了自己,请务必在评论中提出任何问题。

Tam*_*mas 5

您可以更新原始e参考:

公共类全局变量
{
    公共国际E;
}

静态无效主()
{
    var globals = new Globals { E = 1 };
    var _scriptState = CSharpScript.RunAsync("System.Console.WriteLine(E)", globals: globals).Result;
    全局变量.E = 2;
    var x = _scriptState.ContinueWithAsync("System.Console.WriteLine(E)").Result;
}