我试图在.NET 4.5中掌握异步方法语法.我以为我已经明白了究竟例子然而无论异步方法的类型是什么(即Task<T>),我总是得到相同类型的错误错误的转换回T-我明白这是相当多的自动.以下代码生成错误:
无法隐式将类型'
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为'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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我显式地转换结果,它也会失败.这个:
public List<int> TestGetMethod()
{
return (List<int>)GetIdList(); // compiler error on this line
}
Run Code Online (Sandbox Code Playgroud)
有点可以预见会导致此错误:
无法将类型'
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为'System.Collections.Generic.List<int>'
任何帮助非常感谢.
我的一些代码有问题,特别是这部分。我正在调用一个async返回 a的方法Task<List<>>(无法返回常规列表,因为该方法是异步的)。但是,我无法将其转换为常规列表,这正是我所需要的。这甚至可能吗?如果是这样,有人可以帮忙吗?:)
static void Main(string[] args) {
Program p = new Program();
List<Product> products = p.getProducts();
}
public async Task<List<Product>> getProducts() {
// calling woocommerce api
MyRestApi rest = new MyRestApi("http://someurl.com/wp-json/wc/v2", "consumer key", "consumer secret");
WCObject wc = new WCObject(rest);
List<Product> products = await wc.Product.GetAll();
return await Task.Run(() => new List<Product>(products));
}
Run Code Online (Sandbox Code Playgroud)