【发布时间】:2014-09-25 00:09:13
【问题描述】:
当我通过 HttpClient 对象从 web api 获取数据时,我有异步方法。 我打印出响应字符串,我可以看到我有正确的数据。
我还将响应转换为我的自定义类的数组,效果很好(我可以将属性记录到控制台)。
当我按索引打印属性时,一切正常:
Debug.WriteLine("B: " + brands[0].Brand);
但是当我枚举数组时它没有记录数据,它看起来像是包含空字符串,为什么?:
foreach (Brand brand in brands)
{
Debug.WriteLine("BRAND: ", brand.Brand.ToString()); // Prints just BRAND:
}
这就是我的方法的样子:
public static async Task<Brand[]> LoadBrandsAsync()
{
Brand[] brands = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(serviceUrl);
HttpResponseMessage response = await client.GetAsync("Brands");
try
{
brands = await response.Content.ReadAsAsync<Brand[]>();
Debug.WriteLine("Count: " + brands.Count());
Debug.WriteLine("B: " + brands[0].Brand); // This works fine
Debug.WriteLine("B: " + brands[0].Sales); // it print out the data
foreach (Brand brand in brands)
{
// This does't work, WHY?
Debug.WriteLine("BRAND: ", brand.Brand.ToString() + ", " + brand. Sales.ToString());
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
return brands;
}
有人能回答为什么数组中的对象在枚举时看起来像空吗?
【问题讨论】:
-
只是一个温和的书呆子:你没有枚举你正在迭代它的数组。
标签: c# async-await