如何在不知道 class 的情况下从另一个 dll 调用 class 的函数?

How to call a function of a class from another dll without knowing the class?

我目前在做的项目(归结为这个问题)由3部分组成:

    - A server class
    - An interface
    - Plugins that implement the interface

现在我想从插件发送消息,该插件通过服务器项目中的反射作为 DLL 加载到连接的客户端。当然,我的服务器 class 需要一个功能来发送我的消息。现在的问题是如何从我的插件调用这个函数,它只知道接口而无法获得服务器的单例实例 class.

理论上我会说,我在接口中设置了一个空的函数指针,然后在加载插件时,让它指向我的方法,然后通过它向客户端发送消息。我唯一找到的是委托,不能在接口中定义。那么有什么替代方案呢?

下面是用于说明的伪代码。我希望您了解我想做什么,并能帮助我找到解决方案。重要的是,插件不知道有关服务器的任何功能,只知道 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);
    }
}

有很多方法可以从插件中获取回调(如果我理解正确的话)

为什么不直接使用事件、动作或函数

public class ISomething
{
   public Action<string,ISomething> MyCallBack { get; set; }
}

public class Server
{
   private List<ISomething> mPlugins = new List<ISomething>();

   public Server()
   {
      LoadPlugins();
   }

   private void LoadPlugins()
   {
      foreach (var plugin in mPlugins)
         plugin.MyCallBack += MyCallBack;
   }

   private void MyCallBack(string message, ISomething plugin)
   {
      Console.WriteLine(message);
   }
}