加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Interface方法的CreateDelegate

发布时间:2020-12-16 01:47:03 所属栏目:百科 来源:网络整理
导读:我正在努力查看我出错的地方,创建一个接口方法的委托 我的代码如下: private static FuncHtmlDocument,IObservableIData FindScrapeMethod(ICrawlerStrategy crawler,string scrapeDelegate){ FuncHtmlDocument,IObservableIData action; var fullDelegateN
我正在努力查看我出错的地方,创建一个接口方法的委托

我的代码如下:

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)

在尝试创建委托时,我收到“绑定到目标方法的错误”.当我步骤代码时,

>该方法不为null,因此它显然可以在类型上找到方法
>实例也不是null

任何指针,请.

谢谢

小号

解决方法

您的问题是传递给CreateDelegate的类型.

函数的返回值是

Func<HtmlDocument,IObservable<IData>>

因此,您的代表的类型是

Func<Func<HtmlDocument,IObservable<IData>>>

所以改变这一行(你必须修复其他人才能匹配)

action = (Func<Func<HtmlDocument,IObservable<IData>>>)
          Delegate.CreateDelegate(typeof(Func<Func<HtmlDocument,IObservable<IData>>>),method);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读