【发布时间】:2015-08-02 22:11:21
【问题描述】:
我有一个主程序,它动态加载 DLL 文件并激活一个包含所有核心操作的类文件,假设类继承和插件接口。
我在主窗体上有两个方法,我通过插件接口作为操作传递,我在程序集加载期间将方法分配给插件内的操作,然后我调用这些操作并传递一个执行的值主程序中的方法并执行其任务。
我在这里想知道的是,除了使用 Action/Func 委托之外,是否还有其他替代方法,而不引用主程序(两者必须保持独立,仅与 IPlugin 接口相关,IPlugin 接口是在主程序和插件项目),并且没有在插件 DLL 文件本身中使用任何方法调用。
还是我已经在使用最合适的方法?
--编辑--
//Interface
interface IPlugin
{
Action<string> myAction;
}
//Main Program
public class MainForm
{
void LoadPlugins(Action<string> myMethod)
{
List<Assembly> Assemblies = new List<Assembly>();
foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll")) { Assemblies.Add(Assembly.LoadFile(file)); }
foreach (Assembly a in Assemblies)
{
AppDomain.CurrentDomain.Load(a.GetName());
foreach (Type x in a.GetTypes())
{
if (x.IsInterface || x.IsAbstract || x.GetInterface(typeof(IPlugin).FullName) == null) { continue; }
IPlugin plugin = (IPlugin)Activator.CreateInstance(x);
plugin.myAction = myMethod;
}
}
}
void OnLoad()
{
LoadPlugins(UpdateGUI);
}
void UpdateGUI(string Message)
{
txtBlockReport.Text += Message;
}
}
//Plugin compiled as DLL, implementing & referencing IPlugin Interface.
public class MyPlugin : IPlugin
{
public Action<string> myAction { get; set; }
void OnLoad()
{
myAction("Plugin Loaded");
}
}
【问题讨论】:
-
您可以让主表单(或其他对象)实现另一个接口,该接口公开这两种方法,然后以这种方式将其传递给插件。
-
主程序有一个实现插件接口的类,我在主窗体逻辑中为按钮调用接口。示例:主窗体生成控件并设置一个Buttons 点击EH 执行(Button.Tag as IPlugin).Method("Argument"); - 我打算在接口中创建方法并使用相同的方法,但问题是逻辑上我正在考虑它在 DLL 文件中执行一个方法,而我希望 DLL 文件在主程序中执行一个方法。
-
@ColinMurphy 太多令人费解的描述性信息。您如何尝试发布一些代码? MCVE 会很棒
-
我已经更新了我的主要帖子,其中包含我目前正在做的事情的示例代码,并希望做。 Action
有效,但我也想知道在保持两个程序分开的同时是否还有其他替代方法。 -
你想替换/避免什么?