【发布时间】:2023-03-21 00:31:01
【问题描述】:
我有一个使用 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;
}
为了更清楚: 在我的应用程序中,有一个特定的事件。用户可以使用一些 C# 代码定义事件发生时会发生什么(此代码经常更改)。现在重点是 - 我需要将事件参数传递给脚本,以便用户可以在代码中使用它。同时,我需要保持引擎状态,因为用户可能已经定义了一些他想下次使用的变量。
我已经可以传递事件参数(并在脚本中像 e 一样引用它),但只是第一次(即当 ScriptState 为空并且我创建一个新参数时)。下次运行此脚本或其他脚本时 (ScriptState.ContinueWithAsync),事件 args 与之前的状态相同,因为我不知道如何更新它们。
如何访问e 全局并将其设置为新值?我已经尝试通过Variables 列表访问它(如您在代码中看到的那样),但似乎全局变量并未保留在列表中。同时在运行第一个脚本时我不能添加任何变量,因为ScriptVariable 类有一个内部构造函数。 (ScriptState.Variables.Add( ScriptVariable ))
感谢您的帮助。我希望我已经阐明了自己,请务必在 cmets 中提出任何问题。
【问题讨论】: