将静态方法添加到 IronPython 范围

发布于 2024-09-17 09:36:28 字数 310 浏览 1 评论 0原文

假设我有以下代码:

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

在 IronPython 中,我希望:

Bar()

不必包含 Foo 就行了。现在,我知道我可以说:

var Bar = Foo.Bar
Bar()

但我想使用 SetVariable 将 Bar 添加到我的 C# 代码中的 ScriptScope。我该怎么做?

Assume I have the following code:

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叫嚣ゝ 2024-09-24 09:36:40

创建方法委托并设置范围。

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

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文