c# - 插件架构和共享接口(interface)问题

标签 c# plugins interface

我正在使用 C# 插件架构。

插件是公开一堆呈现器的 D​​LL,这些呈现器是实现 IPresenter 的对象。界面。

IPresenter接口(interface)在所有插件共享的 DLL 中可用。

演示者还可以实现由 IAction 定义的其他方法接口(interface),例如 ILoadAction , ISaveAction

这些接口(interface)也由同一个 DLL 共享,因此所有插件都可以有实现此类接口(interface)的呈现器。

案例:我有presenter X在插件中A它实现了 IPresenter接口(interface)和 ILoadAction 接口(interface)。

在插件中 B ,我要求插件架构给我一个演示者X .这给了我一个 <i>IPresenter</i>目的。

要调用该演示者的 LoadAction 方法,我必须将演示者转换为 ILoadAction .

问题:如果我删除 ILoadAction来自主持人X在插件中A ,插件中的代码 B即使演示者没有实现 ILoadAction 仍然会编译不再。

在这种情况下,我希望得到编译器的警告。

实际上,我想避免强制转换为某个 IAction一直。

问题:如何处理?

最佳答案

恐怕编译器不会在这里帮助你。插件 A 可以在构建 B 之前、期间或之后随时更改,因此您的插件架构需要应对可能的接口(interface)丢失 - 为接口(interface)返回空值或抛出异常。

至于获取正确类型的项目,这可以使用泛型来实现:

T IPresenter.GetAction <T> where T : class, IAction ()
{
   return (T) GetAction (typeof T)
}

所以转换是在 GetAction 方法中完成的,而不是调用者(某种程度上):

var action = PluginA.GetAction <ILoadAction> ();

编辑:

如果在调用中执行 <> 太多,请尝试:

bool GetAction<T> (out T a) where T : class, IAction
{
  // stuff
  return interface_found; // or throw an exception?
}

然后你可以这样做:

ILoadAction action;
if (!PluginA.GetAction (out action))
{
   // failed to get interface!
}

关于c# - 插件架构和共享接口(interface)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1872994/

相关文章:

swift - 有没有办法在函数中使用通用协议(protocol)作为数据类型?

c# - 在 Controller 操作之前调用的 WebAPI 函数

c# - 从 Active Directory 中读取已删除的用户

javascript - 传单 map 似乎缺少建筑物。有什么选择?

macos - Qt + CMake for OSX bundle : Cocoa Platform Plugin

java - 我可以限制哪些类可以实现接口(interface)吗?

c# - 如何发送到剪贴板 datagridview 内容,如 CTRL-C

c# - Dialog Stack.Forward 在 Context.Forward 工作的地方不起作用

ubuntu - JMeter:插件管理器在 Ubuntu 的选项 > 插件管理器中不显示任何更新

使用模板实现接口(interface)的c++编译错误