概述:
我正在编写一个应用程序来动态加载 .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