2011-12-16 232 views
2

我正在爲使用C#編寫的.NET應用程序編寫一個簡單的插件系統。我正在嘗試使用IronPython來實現這一點。在C#中實現一個.NET接口實例化IronPython類型

在我的.NET代碼中,我創建了一個IPlugin接口,所有的插件都必須實現。 該程序的用戶指定了一個python文件的路徑,該文件可以包含許多實現IPlugin的類,以及不包含這些類的類。

我遇到的問題是我有了一個CompiledCode對象及其ScriptScope,我想遍歷代碼中定義的所有類,然後實例化那些實現IPlugin接口的新實例。我不知道如何做到這一點,除了盲目實例化所有IronPythonType對象,然後檢查生成的對象是否爲IPlugin類型。這並不理想。

以下是我現在使用的代碼片段。

 public void LoadPlugins(string filePath) { 
     try { 
      ScriptSource script = _ironPythonEngine.CreateScriptSourceFromFile(filePath); 
      CompiledCode code = script.Compile(); 
      ScriptScope scope = _ironPythonEngine.CreateScope(); 
      var result = code.Execute(scope); 

      foreach (var obj in scope.GetItems().Where(kvp => kvp.Value is PythonType)) { 
       var value = obj.Value; 
       var newObject = value(); 
       if (newObject is IPlugin) { 
        // Success. Call IPlugin methods. 
       } else { 
        // Just created an instance of something that is not an IPlugin - this is not ideal. 
       } 
      } 

     } catch (Exception) { 
      // Handle exceptions 
     } 
    } 

回答

2

嘗試PythonOps.IsSubClass()。我沒有測試過,但這應該工作:

if(PythonOps.IsSubClass(value, DynamicHelpers.GetPythonTypeFromType(typeof(IPlugin))) { 
    // Success. Call IPlugin methods. 
} 
+0

這個作品,歡呼! – Optical 2011-12-16 23:57:23