在以下代码段中,如何将对象作为参数传递给脚本中的方法?
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);
最佳答案
Globals
类型应包含所有全局变量声明作为其属性。
假设您为脚本获得了正确的引用:
var metadata = MetadataReference.CreateFromFile(typeof(MyClass).Assembly.Location);
选项1
您需要定义一个MyClass类型的全局变量:
public class Globals
{
public MyClass C { get; set; }
}
并将其用作
Globals
类型: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
属性。这应该够了吧。选项2
在您的情况下,如果您打算多次调用脚本,则创建一个委托(delegate)可能是有意义的:
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 });
选项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);
关于c# - 如何将对象传递给脚本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38278701/