如何将对象传递给脚本?

2024-01-11

在下面的代码片段中,如何将对象作为参数传递给脚本中的方法?

var c = new MyAssembly.MyClass()
{
    Description = "test"
};

var code = "using MyAssembly;" +
           "public class TestClass {" +
           "  public bool HelloWorld(MyClass c) {" +
           "    return c == null;" +
           "  }" +
           "}";

var script = CSharpScript.Create(code, options, typeof(MyAssembly.MyClass));
var call = await script.ContinueWith<int>("new TestClass().HelloWorld()", options).RunAsync(c);

The Globalstype 应该保存任何全局变量声明作为它的属性。

假设您获得了脚本的正确引用:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将对象传递给脚本? 的相关文章

随机推荐