2012-02-05 89 views
1

我有一個非靜態的C#類和一些實例方法,我需要從IronPython腳本調用。目前,我做這樣說:C#,IronPython - 從非靜態類導入(?)

scope.SetVariable("class", instanceOfClass); 
在C#代碼

class.SomeMethod(args) 

腳本。

我想要的是能夠調用這個類的方法,而不用每次在腳本中添加class.。每個腳本都有其自己的類實例,並且在一個腳本中只使用一個實例。

如果這個類是靜態的,解決方案將是from ClassName import *,但據我所知,非靜態類沒有類似的構造。

這怎麼辦?我有一些想法(例如使用反射,或以編程方式在Python源代碼中添加class.),但它們過於複雜,甚至可能無法實現。

UPD:

問題通過使用這樣的Python代碼(實際腳本之前)解決:

def Method1(arg1): # for simple method 
    class.Method1(arg1) 

def Method2(arg = 123): # for default values 
    class.Method2(arg) 

def Method3(*args): # for params 
    class.Method3(args) 

# so on 

回答

2

from ClassName import *實際上是from namespace import type。該語句使得該類型可以通過Python中的類型名稱使用。如果這個類是靜態的,它沒有區別。考慮這個示例代碼 - 環境是靜態類。

import clr 
from System import Environment 
print Environment.CurrentDirectory 

要解決您的問題,請將類委託注入到ScriptScope中的類函數中,而不是類本身。

Sample類

public class Foo { 
     public string GetMyString(string input) { 
      return input; 
     } 
    } 

使用

private static void Main(string[] args) { 
      ScriptEngine engine = Python.CreateEngine(); 

      string script = "x = GetMyString('value')"; 

      Foo foo = new Foo(); 

      ScriptSource scriptSource = engine.CreateScriptSourceFromString(script); 

      ScriptScope scope = engine.CreateScope(); 
      scope.SetVariable("GetMyString", new Func<string, string>(foo.GetMyString)); 

      scriptSource.Execute(scope); 

      string output = scope.GetVariable<string>("x"); 
      Console.WriteLine(output); 
     } 

打印

+0

它的工作原理,當然,但班裏有很多方法,其中一些與'params'論證ts和默認值,所以不可能(我認爲)爲它們創建'Func <>'和'Action <>'。 – aplavin 2012-02-05 11:01:47

+0

關於導入 - 類似'從System.Console導入*'和'WriteLine(123)''這樣的代碼有效,所以它不僅從名稱空間導入類型,還從類型導入類型。 – aplavin 2012-02-05 11:04:27

+0

您可能不想將該類型的成員導入全局範圍,我不相信這會提供大多數Python用戶熟悉的體驗。 – 2012-02-05 12:09:24