2011-12-16 230 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