如何将一个对象传递给脚本?

8
在下面的代码片段中,我如何将我的对象作为参数传递给脚本中的方法?
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);

阅读文档:https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples - Tommy
但是你似乎需要一个编译器来编译你的类,而不是一个脚本引擎来执行一些代码。使用CSharpSyntaxTree.ParseText: http://www.tugberkugurlu.com/archive/compiling-c-sharp-code-into-memory-and-executing-it-with-roslyn - Tommy
@Tommy 这些示例应该展示如何将脚本参数化,但在我的情况下,我想将参数传递给方法,而这些示例并没有展示。ParseText 看起来很有趣,但我不想在执行代码之前创建临时程序集。 - Ivan-Mark Debono
1个回答

13
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变量和一个在Globals中的C属性。这应该会解决问题。


选项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 });

选项3

在你的情况下,甚至不需要传递任何全局变量


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);

很棒的答案,所有选项都能按预期工作。这些示例展示了使用Roslyn可能实现的功能,并应该包含在样例中。 - Ivan-Mark Debono

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接