开发者

CreateDelegate on Interface method

开发者 https://www.devze.com 2023-03-31 17:01 出处:网络
I\'m struggling to see where I am going wrong wrt creating a delegate to an interface method My code is as follows:

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,

  1. the method is not null so it can obviously find the method on the type
  2. 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号