2012-06-14 85 views
0

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

我正在写一个应用程序来动态加载.dlls并调用它们的方法。

由于.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(); 

(这是我试图修复。dinamically调用该.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 
+0

你试图传递的方法,但你可以只传递对象。这就是传递布尔值的原因。你可能想使用该方法作为委托? –

+0

我想从一个dll调用(调用)一个方法,它接收一个回调方法作为参数。 这基本上是我想要做的,有什么办法可以做到吗? 如果没有办法,我可能不得不查看整个应用程序结构。 –

+1

不应该第一个'crawlMethod.Invoke(...);'是'setCallbackMethod.Invoke(...);'? –

回答

2

我假设你有一个委托类型像这样的传球该方法SetCallback

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

然后,如果你将它转换为这种委托类型这样你就可以通过Notify方法:

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

WOW! 谢谢你一堆。 这解决了我的问题。 再次感谢,真的:) –

相关问题