2010-09-03 12 views
6

Hinzufügen gehe ich davon aus den folgenden Code haben:statische Methode Iron Umfang

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

In Iron möchte ich haben mag:

Bar() 

Ohne den Foo auf der Leitung schließen zu müssen. Nun, ich weiß, was ich sagen kann:

var Bar = Foo.Bar 
Bar() 

Aber ich möchte Bar zum ScriptScope in meinem C# Code hinzufügen SetVariable verwenden. Wie kann ich das machen?

Antwort

9

Delegat für Methode erstellen und in Geltungsbereich festlegen.

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

Funktioniert perfekt. Ich kippe Ihnen meine Haube. – Amy