如何动态调用接收回调作为参数的 dll 方法
本文关键字:回调 参数 方法 dll 何动态 动态 调用 | 更新日期: 2023-09-27 18:37:17
概述:
我正在编写一个应用程序来动态加载 .dll 并调用它们的方法。
由于 .dll 在后台执行大量 I/O,因此我进行了回调以通知 UI "那里"
发生了什么代码片段:
dllName = (string) e.Argument;
// Assembling Complete path for the .dll file
completePath = Path.Combine(ConfigurationManager.AppSettings["DllsFolder"], dllName);
Assembly assembler = Assembly.LoadFrom (completePath);
// Creating Instance of Crawler Object (Dynamically)
dllWithoutExtension = Path.GetFileNameWithoutExtension (dllName);
Type crawlerType = assembler.GetType (dllWithoutExtension + ".Crawler");
object crawlerObj = assembler.CreateInstance (crawlerType.FullName);
// Fetching reference to the methods that must be invoked
MethodInfo crawlMethod = crawlerType.GetMethod ("StartCrawling");
MethodInfo setCallbackMethod = crawlerType.GetMethod ("SetCallback");
目前为止,一切都好。问题是,即使我已经声明了"回调"方法
public void Notify (string courseName, int subjects, int semesters)
{
string course = courseName;
int a = subjects;
int b = semesters;
}
此代码有效(仅用于测试回调声明是否有效)
Crawler crawler = new Crawler();
crawler.SetCallback (Notify);
crawler.StartCrawling();
虽然这不起作用(这是我试图解决的问题。动态调用 .dll 方法,将回调作为参数传递)
setCallbackMethod.Invoke(crawlerObj, new object[] { Notify }); // this method fails, bc its a callback parameter
crawlMethod.Invoke(crawlerObj, new object[] {true} ); // This method works, bc its a bool parameter
我假设你有这样的委托类型,用于将方法传递给SetCallback
:
public delegate void CrawlerCallback(string courseName, int subjects, int semesters);
然后,如果将 Notify
方法强制转换为此委托类型,则可以传递该方法,如下所示:
setCallbackMethod.Invoke(crawlerObj, new object[] { (CrawlerCallback)Notify });