【问题标题】:For each loop iterates the first empty element of a collection对于每个循环,迭代集合的第一个空元素
【发布时间】:2013-01-18 12:33:17
【问题描述】:

我在 vb .net 集合中添加了 2 个元素。调试时我可以看到 .count = 2。

如果监视集合中的元素,我通常会看到零索引中的第一个空元素,然后是我添加的两个元素。

问题是当我用 For Each Next 循环迭代集合时,空元素被迭代而最后一个元素没有被迭代。

这是结构的声明方式

Structure bstCategory
    Dim categoryCode As String
    Dim categoryVersion As String
End Structure

这就是集合的填充方式

 With ci.tItem.information
    .categories = New Collection
    Dim additionalClassification As bstCategory
    additionalClassification.categoryCode = "1"
    additionalClassification.categoryVersion = "A"
    .categories.Add(additionalClassification)
    additionalClassification.categoryCode = "2"
    additionalClassification.categoryVersion = "B"
    .categories.Add(additionalClassification)
End With

这就是集合的迭代方式

For Each category As bstCategory In ci.tItem.information.categories
        ValidateCategory(categorycode)
Next

我做错了什么?

【问题讨论】:

  • ` Dim names As New Microsoft.VisualBasic.Collection() names.Add("John") names.Add(2) For Each x In names Console.WriteLine(x) Next` 对我有用.你试过重启VS吗?
  • 您可以发布您的bstCategory 的代码吗?如果它是您创建的类,请检查代码
  • 我重启了VS,但问题依旧。
  • bstCategory 是一个结构类型: Structure bstCategory Dim categoryCode As String Dim categoryVersion As String End Structure
  • 如果您展示了 a:categories 的创建方式和 b:categories 的填充方式,将会有所帮助。

标签: .net vb.net collections iteration


【解决方案1】:

我无法重现您的问题,它适用于我在 vs2010 目标 .net 2.0 中使用 vb.net

这是我根据您的代码尝试的:

Module Module1

    Structure bstCategory
        Dim Code As String
        Dim Version As String
    End Structure

    Sub Main()

        Dim categories As New Collection()
        Dim c As New bstCategory
        c.Code = "1"
        c.Version = "1"
        categories.Add(c)
        categories.Add(c)

        For Each category As bstCategory In categories
            Console.WriteLine(category.Code)
        Next

    End Sub

End Module

如果 For Each 给您带来了这种奇怪的行为,您可以将其更改为使用 For。

For i As Integer = 1 To categories.Count
   Console.WriteLine(categories(i).Code)
Next

无论如何,您所面临的情况很奇怪,我的建议是在 Google 中查找 index 0 文本。我做到了,并且有一些页面在讨论这个问题,所以你的答案可能就在那里。

Google for:“为基于 1 的数组调整的空占位符”

希望有帮助!

这是一张图片,显示了集合中从 0 到 2 的 3 个值,但是,当迭代时,它只进入两次,打印出 1 两次。

【讨论】:

  • 如果我使用 for 而不是 For Each 它可以工作,但是我在相同的代码中使用了很多 For each 循环,如果长时间工作错误,我会担心
猜你喜欢
  • 1970-01-01
  • 2020-07-19
  • 2018-12-09
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 2023-04-08
相关资源
最近更新 更多