在C#中实例化实现.NET接口的IronPython类型
我正在为用C#编写的.NET应用程序编写一个简单的插件系统。我正在尝试使用IronPython来实现这一点 在我的.NET代码中,我创建了一个接口IPlugin,所有插件都必须实现它。 程序的用户指定python文件的路径,该文件中可以有许多实现IPlugin的类,也可以有没有实现IPlugin的类 我遇到的问题是,一旦获得CompiledCode对象及其ScriptScope,我想迭代代码中定义的所有类,然后实例化实现IPlugin接口的类的新实例。除了盲目地实例化所有IronPythonType对象,然后检查生成的对象是否为IPlugin类型之外,我不知道如何做到这一点。这并不理想 下面是我目前拥有的代码片段在C#中实例化实现.NET接口的IronPython类型,c#,.net,scripting,integration,ironpython,C#,.net,Scripting,Integration,Ironpython,我正在为用C#编写的.NET应用程序编写一个简单的插件系统。我正在尝试使用IronPython来实现这一点 在我的.NET代码中,我创建了一个接口IPlugin,所有插件都必须实现它。 程序的用户指定python文件的路径,该文件中可以有许多实现IPlugin的类,也可以有没有实现IPlugin的类 我遇到的问题是,一旦获得CompiledCode对象及其ScriptScope,我想迭代代码中定义的所有类,然后实例化实现IPlugin接口的类的新实例。除了盲目地实例化所有IronPythonTy
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
}
}
请尝试
PythonOps.IsSubClass()
。我还没有测试过,但这应该可以:
if(PythonOps.IsSubClass(value, DynamicHelpers.GetPythonTypeFromType(typeof(IPlugin))) {
// Success. Call IPlugin methods.
}