我正在尝试掌握 .NET 4.5 中的异步方法语法。我认为我已经完全理解了这些示例,但是无论异步方法的类型是什么(即Task<T>
),我总是在转换回相同类型的错误T
- 我理解这几乎是自动的。以下代码会产生错误:
无法隐式转换类型'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;
}
}
如果我也显式地转换结果,它就会失败。这:
public List<int> TestGetMethod()
{
return (List<int>)GetIdList(); // compiler error on this line
}
在某种程度上可以预见会导致此错误:
无法转换类型'System.Threading.Tasks.Task<System.Collections.Generic.List<int>>
' to 'System.Collections.Generic.List<int>
'
非常感谢任何帮助。
您的示例的主要问题是无法隐式转换Task<T>
将类型返回到基类T
类型。您需要使用 Task.Result 属性。请注意,Task.Result 将阻止异步代码,应谨慎使用。
试试这个:
public List<int> TestGetMethod()
{
return GetIdList().Result;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)