我正在努力查看我出错的地方,创建了一个接口方法的委托
我的代码如下:
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;
}
接口声明是
public interface ICrawlerStrategy
{
Func<HtmlDocument, IObservable<IData>> ExtractorAsync();
}
实施类如下
public class MyCrawler : ICrawlerStrategy
{
<snip>
Func<HtmlDocument, IObservable<IData>> ICrawlerStrategy.ExtractorAsync()
{
return (doc) => AsyncScraper(doc);
}
}
Edit1 - 根据@Yahia的要求:
public IObservable<IData> AsyncScraper(HtmlDocument page)
尝试创建委托时,我收到“绑定到目标方法的错误”。当我执行代码时,
任何指针,请。
THX
取值
答案 0 :(得分:7)
您的问题属于您传递给CreateDelegate的类型。
您的函数的返回值是
Func<HtmlDocument, IObservable<IData>>
因此委托的类型为
Func<Func<HtmlDocument, IObservable<IData>>>
所以改变这一行(你必须修复其他人才能匹配)
action = (Func<Func<HtmlDocument, IObservable<IData>>>)
Delegate.CreateDelegate(typeof(Func<Func<HtmlDocument, IObservable<IData>>>), crawler, method);