VB.NET For Each Loop在一次迭代后退出

时间:2013-08-19 20:39:49

标签: vb.net

我有一个For Each循环只迭代1个元素。它在我的测试中从32个中的第6个元素开始,恰好是comp.includeMe评估为True的元素。在执行外部if语句之后,它开始第二次迭代但退出循环并在comp.includeMe评估为false后立即返回。没有错误或警告,我已经验证组件对象中有元素。任何人都可以解释我做错了什么,以及为什么这种语法不起作用?

Public Class BOM    
    Public Property components as New List(Of Component)

    Public Function TotalArea(ByVal adjusted As Boolean) As Double
        Dim total As Double = 0
        For Each comp As Component In components
            If comp.includeMe = True Then
                If adjusted Then
                    total += comp.GetAdjustedSize() * comp.quantity
                Else
                    total += comp.area * comp.quantity
                End If
            End If
        Next
        Return total
    End Function

    public sub Add(byval comp as Component)

        components.add(comp)
    end sub
End Class

Public Class Component
    Public Property quantity as Integer
    Public Property area as Double
    Public Property includeMe as Boolean

    ...
End Class

' object construction
Dim bomlist as New BOM
bomlist.add(comp)

2 个答案:

答案 0 :(得分:1)

在深入挖掘之后,似乎foreach语句正在识别第一个if语句并且仅在值为真时才提取值。我意识到我只有一个组件,includeMe Boolean设置为true。在我将其他组件设置为true之后,我观察到For Each完全重复次数为includeMe = True的组件数

答案 1 :(得分:0)

我建议添加一些调试语句以协助调试:

Public Class BOM    
    Public Property components as New List(Of Component)

    Public Function TotalArea(ByVal adjusted As Boolean) As Double
        Dim total As Double = 0
        Debug.Print(components.Count)
        For Each comp As Component In components
            Debug.Print(comp.includeMe)  
            If comp.includeMe = True Then
                If adjusted Then
                    total += comp.GetAdjustedSize() * comp.quantity
                Else
                    total += comp.area * comp.quantity
                End If
            End If
        Next
        Return total
    End Function

    public sub Add(byval comp as Component)

        components.add(comp)
    end sub
End Class
相关问题