gpt4 book ai didi

c# - 在 C# 中实例化实现 .NET 接口(interface)的 IronPython 类型

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:42 26 4
gpt4 key购买 nike

我正在为用 C# 编写的 .NET 应用程序编写一个简单的插件系统。我正在尝试使用 IronPython 来完成此任务。

在我的 .NET 代码中,我创建了一个接口(interface) IPlugin,所有插件都必须实现该接口(interface)。该程序的用户指定 python 文件的路径,其中可以包含许多实现 IPlugin 的类,以及不实现 IPlugin 的类。

我遇到的问题是,一旦获得 CompiledCode 对象及其 ScriptScope,我想遍历代码中定义的所有类,然后实例化实现 IPlugin 接口(interface)的类的新实例。我不知道该怎么做,除了盲目地实例化所有 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
}
}

最佳答案

试试 PythonOps.IsSubClass()。我还没有测试过,但这应该有效:

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

关于c# - 在 C# 中实例化实现 .NET 接口(interface)的 IronPython 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8540495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com