-1

我有一个仅迭代 1 个元素的 For Each 循环。它从我的测试中 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)
4

2 回答 2

1

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

于 2013-08-19T21:18:10.153 回答
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
于 2013-08-19T21:11:58.683 回答