如何动态调用接收回调作为参数的dll方法?

时间:2012-06-14 16:42:42

标签: c# reflection callback invoke

概述:

我正在编写一个动态加载.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

1 个答案:

答案 0 :(得分:2)

我假设你有一个这样的委托类型,用于将方法传递给SetCallback

public delegate void CrawlerCallback(string courseName, int subjects, int semesters);

然后,如果将它转换为此委托类型,则可以传递Notify方法:

setCallbackMethod.Invoke(crawlerObj, new object[] { (CrawlerCallback)Notify });