开发者

Adding static method to IronPython scope

开发者 https://www.devze.com 2023-01-14 03:11 出处:网络
Assume I have the following code: public static class Foo { public static void Bar() {} } 开发者_StackOverflow中文版In IronPython, I would like to have:

Assume I have the following code:

public static class Foo
{
    public static void Bar() {}
}

开发者_StackOverflow中文版In IronPython, I would like to have:

Bar()

Without having to include the Foo on the line. Now, I know I can say:

var Bar = Foo.Bar
Bar()

But I would like to add Bar to the ScriptScope in my C# code using SetVariable. How can I do this?


Create delegate to method and set in to scope.

public class Program
{
    public static void Main(string[] args)
    {
        var python = Python.CreateEngine();
        var scriptScope = python.CreateScope();
        scriptScope.SetVariable("Print", new Action<int>(Bar.Print));

        python.Execute(
            "Print(10)",
            scriptScope
            );
    }

}

public static class Bar
{
    public static void Print(int a)
    {
        Console.WriteLine("Print:{0}", a);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消