不能隐式地从任务&LT转换类型;&GT; [英] Cannot implicitly convert type from Task<>
问题描述
我试图掌握异步方法语法.NET 4.5。我想我已经理解的例子正好但是无论异步方法的类型是什么(即任务&LT; T&GT;
),我总是得到相同类型的错误的错误转换回 T
- 我明白这是pretty很多自动的。下面code产生错误:
无法隐式转换类型
System.Threading.Tasks.Task&LT; System.Collections.Generic.List&LT; INT&GT;&GT;
到System.Collections.Generic.List&LT; INT&GT;
块引用>公开名单&LT; INT&GT; TestGetMethod()
{
返回GetIdList(); //在这一行编译器错误
}
异步任务&LT;名单,LT; INT&GT;&GT; GetIdList()
{
使用(HttpClient的代理=新的HttpClient())
{
字符串的响应=等待proxy.GetStringAsync(www.test.com);
清单&LT; INT&GT; IDLIST = JsonConvert.DeserializeObject&LT;名单,LT; INT&GT;&GT;();
返回IDLIST;
}
}如果我明确投的结果以及它失败。这样的:
公开名单&LT; INT&GT; TestGetMethod()
{
回报(名单&LT; INT&GT;)GetIdList(); //在这一行编译器错误
}有些美元这个错误p $ pdictably结果:
无法将类型'
System.Threading.Tasks.Task&LT; System.Collections.Generic.List&LT; INT&GT;&GT;
到系统.Collections.Generic.List&LT; INT&GT;
块引用>任何帮助非常AP preciated。
解决方案的主要问题与你的榜样,你不能隐式转换
任务&LT; T&GT;
返回类型为基T
键入。您需要使用Task.Result属性。需要注意的是Task.Result将阻止异步code,故应慎重使用。试试这个:
公开名单&LT; INT&GT; 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 toT
- 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 baseT
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屋!