【问题标题】:Cannot convert from method group to System.Func<string>无法从方法组转换为 System.Func<string>
【发布时间】:2015-04-01 03:21:59
【问题描述】:

我正在使用 .Net 4.0 任务类来使用线程在后台下载 google 网页。问题是如果我的函数有 1 个或多个参数,应用程序将无法编译(idk 如何传递该参数)。所以我想知道如何在 DoWork() 方法中传递函数的参数。

这行得通:

    public Task<String> DoWork() {
        //create task, of which runs our work of a thread pool thread
        return Task.Factory.StartNew<String>(this.DownloadString);

    }


    private String DownloadString()
    {
        using (var wc = new WebClient())
            return wc.DownloadString("http://www.google.com");
    }

这不是:

    public Task<String> DoWork() {
        //create task, of which runs our work of a thread pool thread
        return Task.Factory.StartNew<String>(this.DownloadString);

    }


    private String DownloadString(String uri)
    {
        using (var wc = new WebClient())
            return wc.DownloadString(uri);
    }

错误是:

cannot convert from 'method group' to 'System.Func<string>'

提前谢谢你!

【问题讨论】:

  • 您的第二个 sn-p 应该如何知道要下载什么?你在哪里传递uri 参数?
  • @Blorgbeard,问题是,我不知道怎么通过。
  • 嗯,这就是编译器错误。你的DownloadString 不是Func&lt;string&gt;,它是Func&lt;string,string&gt;。 Task.StartNew 期待前者,而不是后者。

标签: c# wpf .net-4.0 task-parallel-library


【解决方案1】:
return Task.Factory.StartNew(() => DownloadString("https://www.google.com"));

return Task.Factory.StartNew(() =>
            {
                using (var wc = new WebClient())
                    return wc.DownloadString("https://www.google.com");
            });

【讨论】:

    【解决方案2】:
    return Task.Factory.StartNew(() => this.DownloadString("http://...."));
    

    【讨论】:

    • Delegate 'System.Func' 不接受 1 个参数
    • @DanielPascal 我修好了
    • 它有效,谢谢。这很明显,很简单。既然你先回答,我就接受你的。
    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2015-07-31
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多