wpf 无法从方法组转换为 System.Func<string>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29376665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:03:17  来源:igfitidea点击:

Cannot convert from method group to System.Func<string>

c#wpf.net-4.0task-parallel-library

提问by Daniel Pascal

I'm playing a bit with the .Net 4.0 Task class to download the google webpage in background using a thread. The problem is that if my function has 1 or more parameters, the application won't compile (idk how to pass that parameter). So I wonder how can I pass the function's parameter in the DoWork() method.

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

This works:

这有效:

    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");
    }

This doesn't:

这不会:

    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);
    }

The error is:

错误是:

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

Thank you in advance!

先感谢您!

回答by puko

return Task.Factory.StartNew(() => DownloadString("https://www.google.com"));

or

或者

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

回答by EZI

return Task.Factory.StartNew(() => this.DownloadString("http://...."));