CreateDelegate 接口方法
我正在努力找出我在创建接口方法委托时出错的地方
我的代码如下:
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)
当尝试创建委托时,我收到“绑定到目标方法时出错”。当我单步执行代码时,
- 该方法不为空,因此它显然可以找到实例类型上的方法
- 也不为空
任何指针,请。
谢谢
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<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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题在于传递给 CreateDelegate 的类型。
您的函数的返回值是
因此您的委托的类型是
因此更改此行(您还必须修复其他行以匹配)
Your problem is in the type that you pass to CreateDelegate.
The return value of your function is
Therefore the type of your delegate is
So change this line (you'll have to fix others as well to match)