CreateDelegate on Interface method
I'm struggling to see where I am going wrong wrt creating a delegate to an interface method
My code is as follows:
private static Func<HtmlDocument, IObservable<IData>> FindScrapeMethod(ICrawlerStrategy crawler, string scrapeDelegate)
{
Func<HtmlDocument, IObservable<IData>> action;
var fullDelegateName = String.Format("ICrawlerStrategy.{0}", scrapeDelegate);
if (!_delegateCache.TryGetValue(fullDelegateName, out action))
{
var method = typeof(ICrawlerStrategy).GetMethod(scrapeDelegate, BindingFlags.Public | BindingFlags.Instance );
action = (Func<HtmlDocument, IObservable<IData>>)
Delegate.CreateDelegate(typeof(Func<HtmlDocument, IObservable<IData>>), crawler, method);
_delegateCache.Add(fullDelegateName, action);
}
return action;
}
The interface declaration is
public interface ICrawlerStrategy
{
Func<HtmlDocument, IObservable&开发者_Go百科lt;IData>> ExtractorAsync();
}
The implementing class is as follows
public class MyCrawler : ICrawlerStrategy
{
<snip>
Func<HtmlDocument, IObservable<IData>> ICrawlerStrategy.ExtractorAsync()
{
return (doc) => AsyncScraper(doc);
}
}
Edit1 - as requested by @Yahia:
public IObservable<IData> AsyncScraper(HtmlDocument page)
When trying to create the delegate I'm getting an "Error binding to target method". When I step the code,
- the method is not null so it can obviously find the method on the type
- the instance is also not null as well
Any pointers, pls.
Thx
S
Your problem is in the type that you pass to CreateDelegate.
The return value of your function is
Func<HtmlDocument, IObservable<IData>>
Therefore the type of your delegate is
Func<Func<HtmlDocument, IObservable<IData>>>
So change this line (you'll have to fix others as well to match)
action = (Func<Func<HtmlDocument, IObservable<IData>>>)
Delegate.CreateDelegate(typeof(Func<Func<HtmlDocument, IObservable<IData>>>), crawler, method);
精彩评论