我正在开发一个用 C# 编写的应用程序,该应用程序托管 IronPython。我的计划是用户将编写 python 脚本,其中包含实现预定义接口(interface)的类。
类似于:
用C#代码定义接口(interface):
public interface IPlugin
{
void DoSomething();
}
用Python代码实现接口(interface)。
class Plugin(IPlugin):
def DoSomething():
print "Doing stuff."
在我的应用程序中,我加载 python 脚本并执行这些脚本中的类实现的方法。
我想知道:如何获取Python脚本中实现指定接口(interface)的所有类的句柄?
例如:如果我要在 C# 中完成整个事情,我可以通过反射来帮助我,我可以直接加载程序集并执行如下操作:
Assembly assembly = Assembly.LoadFrom("plugin.dll");
Type[] types = assembly.GetTypes();
foreach(Type type in types)
{
foreach(Type interfaceType in type.GetInterface())
{
if(interfaceType == typeof(IPlugin))
{
// gotcha, invoke interface specific methods
}
}
}
当我处理的是 IronPython 脚本而不是程序集时,我该如何做同样的事情?我知道使用 ObjectOperations 和 ScriptScope,如果我知道类的名称,我可以获得该类的句柄 -- as described here -- 但我正在寻找更强大的东西。
最佳答案
您遇到的问题是 IronPython 类不是 .NET 类。 Python 类比 C# 类更加动态,因此 IronPython 类通常是 .NET 对象。
当您在 IronPython 中对 .NET 接口(interface)进行子类化时,它确实会创建一个新的 .NET 类,但多个 Python 类实际上会共享一个后备 .NET 类(只会为该接口(interface)创建一个 .NET 类) IronPython 中子类化的每个 .NET 类型)。
正确的方法是使用 Python 内省(introspection)来收集 IronPython 类对象,并在需要实例化它们的地方使用工厂函数(您可以将其用作委托(delegate) - 将返回的实例转换为接口(interface))。
例如,您可以尝试在 Python 范围内执行:
list_of_classes = IPlugin.\_\_subclasses_\_
关于.net - 查询托管环境中接口(interface)的 IronPython 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/700082/