【发布时间】:2012-01-22 08:28:52
【问题描述】:
我正在为我用 C# 编写的 .NET 应用程序编写一个简单的插件系统。我正在尝试使用 IronPython 来完成此操作。
在我的 .NET 代码中,我创建了一个接口 IPlugin,所有插件都必须实现该接口。 该程序的用户指定了 python 文件的路径,其中可以包含许多实现 IPlugin 的类,以及不实现 IPlugin 的类。
我遇到的问题是,一旦我获得了 CompiledCode 对象及其 ScriptScope,我想遍历代码中定义的所有类,然后实例化那些实现 IPlugin 接口的新实例。我不知道该怎么做,除了盲目地实例化所有 IronPythonType 对象,然后检查结果对象是否是 IPlugin 类型。这并不理想。
这是我目前已有的代码的 sn-p。
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
}
}
【问题讨论】:
标签: c# .net scripting integration ironpython