2010-09-03 18 views
6

假設我有以下代碼:添加靜態方法來IronPython的範圍

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

在IronPython的,我想有:

Bar() 

而不必包括在該行上的Foo。現在,我知道我可以說:

var Bar = Foo.Bar 
Bar() 

但是我想在我的C#代碼中使用SetVariable將Script添加到ScriptScope中。我怎樣才能做到這一點?

回答

9

創建委託給方法並設置爲範圍。

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

完美地工作。我把我的帽子給你。 – Amy 2010-09-03 15:01:24