The Globals
type 应该保存任何全局变量声明作为它的属性。
假设您获得了脚本的正确引用:
var metadata = MetadataReference.CreateFromFile(typeof(MyClass).Assembly.Location);
Option 1
您需要定义一个 MyClass 类型的全局变量:
public class Globals
{
public MyClass C { get; set; }
}
并将其用作Globals
type:
var script =
await CSharpScript.Create(
code: code,
options: ScriptOptions.Default.WithReferences(metadata),
globalsType: typeof(Globals))
.ContinueWith("new TestClass().HelloWorld(C)")
.RunAsync(new Globals { C = c });
var output = script.ReturnValue;
请注意,在ContinueWith
表达式是一个C
变量以及C
财产在Globals
。这应该够了吧。
Option 2
在您的情况下,如果您打算多次调用脚本,创建委托可能是有意义的:
var f =
CSharpScript.Create(
code: code,
options: ScriptOptions.Default.WithReferences(metadata),
globalsType: typeof(Globals))
.ContinueWith("new TestClass().HelloWorld(C)")
.CreateDelegate();
var output = await f(new Globals { C = c });
Option 3
在你的情况下,你甚至不需要通过任何Globals
var f =
await CSharpScript.Create(
code: code,
options: ScriptOptions.Default.WithReferences(metadata))
.ContinueWith<Func<MyClass, bool>>("new TestClass().HelloWorld")
.CreateDelegate()
.Invoke();
var output = f(c);