【问题标题】:Array object empty when enumerating but not when accessing by index枚举时数组对象为空,但按索引访问时不为空
【发布时间】: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


【解决方案1】:

所有Debug.WriteLine 的第一个参数是格式字符串,其元素位置持有者如:"BRAND: {0}, {1}...",在您的情况下没有{0},因此忽略其他参数。

查看Debug.WriteLine 帮助。您也不需要.Tostring() 调用 - 如果参数不是字符串且不是 null,则会自动执行:

  Debug.WriteLine("BRAND: {0}, {1}", brand.Brand, brand.Sales);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    相关资源
    最近更新 更多