For Loop的问题

时间:2019-06-21 11:48:05

标签: vb.net

我遍历了一系列32个标签,希望对每个标签都应用一个函数。但是某些标签彼此不同,我简化了功能只是为了使其更易于理解。

Dim allLabels() As Label = {Label1, Label2, Label3, Label4, ... Label32}
Dim fruits() As String = {"peach", "apple", "orange", "watermelon", "banana", "kiwi" ...}
Dim strBoolean = False

For Each aLabel As Label In allLabels
    For Each fruit As String In fruits
        Dim strFilepath = "C:\Ilikefruit\" + fruit

        If fruit = "apple" Then
            strFilepath = "C:\Ilikeapples\" + fruit

        ElseIf fruit = "orange" Then
            strFilepath = "C:\Ilikeoranges\" + fruit

        ElseIf fruit = "banana" Then
            strFilepath = "C:\Ilikebananas\" + fruit
            strBoolean = True
            Exit For
        End If

        aLabel.Text = strFilepath 
    Next

    If strBoolean = True Then
        Exit For
    End If
Next

我的问题是它再次遍历水果数组,在这种情况下,它将香蕉参数添加到apples目录,最终给我一个错误。我尝试使用Exit For,但没有运气。如何断开链接以仅使用一次参数,然后结束For循环?删除参数(苹果,橙子,香蕉)证明是可行的,但显然会粘贴默认目录。

最终,除了列出的水果外,我还需要每个标签都显示"C:\Ilikefruit\" + fruit

2 个答案:

答案 0 :(得分:0)

在这里我会做出一个大胆的猜测,因为这不是很清楚。首先,将您的代码分成单独的逻辑。

Function GetPathFromFruit(ByVal fruit As String) As String

    If fruit = "apple" Then
        Return "C:\Ilikeapples\" & fruit

    ElseIf fruit = "orange" Then
        Return "C:\Ilikeoranges\" & fruit

    ElseIf fruit = "banana" Then
        Return "C:\Ilikebananas\" & fruit
    End If

    Return "C:\Ilikefruit\" & fruit
End Function

然后按索引循环,这样您就可以同时循环两个数组。

    For index As Integer = 0 To Math.Min(allLabels.Count, fruits.Count) - 1
        allLabels(index).Text = GetPathFromFruit(fruits(index))
    Next

最好有一个Fruit类,该类负责返回信息。

Class Fruit

    Public Property FruitName As String

    Public Sub New(ByVal fruitName As String)
        _FruitName = fruitName
    End Sub

    Public Function GetFilePath()

        If _FruitName = "apple" Then
            Return "C:\Ilikeapples\" & _FruitName

        ElseIf _FruitName = "orange" Then
            Return "C:\Ilikeoranges\" & _FruitName

        ElseIf _FruitName = "banana" Then
            Return "C:\Ilikebananas\" & _FruitName
        End If

        Return "C:\Ilikefruit\" & _FruitName
    End Function

End Class

答案 1 :(得分:0)

这是一个值得深思的例子,我相信您会发现它很有帮助:

$result = array_values($result);

(注意,上面的示例是使用VB版本15,Visual Studio 2017完成的。)