【发布时间】:2019-01-17 00:35:28
【问题描述】:
我目前正在进行的项目(简化为这个问题)由 3 个部分组成:
- A server class
- An interface
- Plugins that implement the interface
现在我想从一个插件向连接的客户端发送一条消息,该插件通过服务器项目中的反射作为 DLL 加载。当然,我需要在我的服务器类中有一个函数来发送我的消息。现在的问题是如何从我的插件中调用这个函数,它只知道接口而无法获得服务器类的单例实例化。
理论上我会说,我在接口中设置了一个空函数指针,然后在加载插件时,让它指向我的方法,然后我通过它向客户端发送消息。我发现的唯一东西是委托,不能在接口中定义。那么有什么替代方案呢?
下面是用于说明的伪代码。我希望你能理解我想做什么,并能让我找到解决方案。重要的是插件不知道服务器的任何功能,只知道 SendMessage 方法。
伪代码:
public class Server{
private List<Plugin> mPlugins = new List<Plugin>();
public Server() {
LoadPlugins();
}
public void SendMessage(string message) {
// Here I would send my message to some client
}
private void LoadPlugins() {
// Here I'm loading my plugins (*.dll) from a specific folder into my mPlugins list
// And while I'm looping through my plugins and loading them, I would set the function pointer to SendMessage(); Like:
plugin.SendMyMessage = SendMessage;
}
}
public interface SomeAPI {
string Name {get;set;}
string Version {get;set;}
delegate void SendMyMessage(string message);
}
public class SomePlugin : SomeAPI {
public string Name {get;set;} = "Some plugin";
public string Version {get;set;} = "v1.0.0";
void SendMessage(string message) {
SendMyMessage(message);
}
}
【问题讨论】: