【问题标题】:Adding static method to IronPython scope将静态方法添加到 IronPython 范围
【发布时间】:2011-04-07 21:32:00
【问题描述】:

假设我有以下代码:

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

在 IronPython 中,我想要:

Bar()

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

var Bar = Foo.Bar
Bar()

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

【问题讨论】:

    标签: c#-4.0 ironpython


    【解决方案1】:

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

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

    【讨论】:

    • 完美运行。我向你倾斜我的帽子。
    猜你喜欢
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2020-06-21
    • 2014-03-23
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多