[英]How to call a class from a project to another project without call the DLL as reference in C#?
[英]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
現在,我想從服務器項目中通過Reflection加載為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);
}
}
有很多方法可以從插件獲取回調(如果我理解正確的話)
為什么不只是使用和事件,動作或功能
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.