不能从 Task<> 隐式转换类型 [英] Cannot implicitly convert type from Task&lt;&gt;

查看:85
本文介绍了不能从 Task<> 隐式转换类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试掌握 .NET 4.5 中的异步方法语法.我以为我已经完全理解了这些示例,但是无论异步方法的类型是什么(即 Task),我总是在转换回 T - 我理解这几乎是自动的.以下代码产生错误:

I am trying to master async method syntax in .NET 4.5. I thought I had understood the examples exactly however no matter what the type of the async method is (ie Task<T>), I always get the same type of error error on the conversion back to T - which I understood was pretty much automatic. The following code produces the error:

无法将类型 'System.Threading.Tasks.Task>' 隐式转换为 'System.Collections.Generic.List;'

Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.List<int>'

public List<int> TestGetMethod()
{
    return GetIdList(); // compiler error on this line
}


async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

如果我也显式地转换结果,它就会失败.这:

It fails if I explicitly cast the result as well. This:

public List<int> TestGetMethod()
{
    return (List<int>)GetIdList();  // compiler error on this line
}

在某种程度上可预见地导致此错误:

somewhat predictably results in this error:

无法将类型System.Threading.Tasks.Task>"转换为System.Collections.Generic.List"'

非常感谢任何帮助.

推荐答案

您的示例的主要问题是您无法将 Task 返回类型隐式转换为基本 T 类型.您需要使用 Task.Result 属性.请注意 Task.Result 会阻塞异步代码,应谨慎使用.

The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

试试这个:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}

这篇关于不能从 Task<> 隐式转换类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆