不能隐式地从任务&LT转换类型;> [英] Cannot implicitly convert type from Task<>

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

问题描述

我试图掌握异步方法语法.NET 4.5。我想我已经理解的例子正好但是无论异步方法的类型是什么(即任务< T> ),我总是得到相同类型的错误的错误转换回 T - 我明白这是pretty很多自动的。下面code产生错误:


  

无法隐式转换类型 System.Threading.Tasks.Task< System.Collections.Generic.List< INT>> System.Collections.Generic.List< INT>


 公开名单< INT> TestGetMethod()
{
    返回GetIdList(); //在这一行编译器错误
}
异步任务<名单,LT; INT>> GetIdList()
{
    使用(HttpClient的代理=新的HttpClient())
    {
        字符串的响应=等待proxy.GetStringAsync(www.test.com);
        清单< INT> IDLIST = JsonConvert.DeserializeObject<名单,LT; INT>>();
        返回IDLIST;
    }
}

如果我明确投的结果以及它失败。这样的:

 公开名单< INT> TestGetMethod()
{
    回报(名单< INT>)GetIdList(); //在这一行编译器错误
}

有些美元这个错误p $ pdictably结果:


  

无法将类型' System.Threading.Tasks.Task< System.Collections.Generic.List< INT>> 系统.Collections.Generic.List< INT>


任何帮助非常AP preciated。


解决方案

的主要问题与你的榜样,你不能隐式转换任务< T> 返回类型为基 T 键入。您需要使用Task.Result属性。需要注意的是Task.Result将阻止异步code,故应慎重使用。

试试这个:

 公开名单< INT> TestGetMethod()
{
    返回GetIdList()结果。
}

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:

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:

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

Any help greatly appreciated.

解决方案

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.

Try this instead:

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

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

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