在Visual Basic中,是否有更好的Goto相当于多个潜艇?

时间:2018-01-22 14:38:52

标签: vb.net goto control-flow

Goto无法进入另一个程序。

如果调用过程中的条件为真,那么我需要调用过程跳到调用过程的末尾。

问题:

 Sub Outer()
    Inner1()
    Inner2()
    Inner3()
  thisline:
  End Sub

  Sub Inner2()
      If condition is true
        goto thisline
      else dostuff
        end if
  End sub

我的解决方案是设置一个变量,然后将其与if语句结合使用,但这也意味着我需要将变量设为公共。

好的,这是实际的代码:

没有任何解决方案:

Sub btnRun_Click() Handles btnRun.Click
    ChooseSaveLocation()
    Case_DatatoGet(DatatoGet:=cmb_DatatoRetrieve.Text)

    WriteDatatoDestination(datachoice:=cmb_DatatoRetrieve.SelectedItem, 
                                 Destination:=cmb_Destination.SelectedItem)
    Debug.Print("---------------Finished with Run----------------")

End Sub

Sub Case_DatatoGet(DatatoGet)
    If DatatoGet = "" Then
        MsgBox("Please click on settings and choose data to retrieve")

    Else
        Select Case DatatoGet
            Case "Company Info"
                GetCompanyInfo(txt_APIUsername.Text, txt_APIPassword.Text)
            Case "Prices"
                GetPrices(txt_APIUsername.Text, txt_APIPassword.Text)
            Case "Balance Sheets"
                Debug.Print("Write a balance sheet sub")
            Case "Income Statements"
                Debug.Print("Write a Income Statement sub")
            Case "Statement of Cash Flows"
                Debug.Print("Write a Statement of Cash Flows sub")
        End Select
    End If

End Sub

使用我的解决方案:

Public ContinueVar
...
Sub btnRun_Click() Handles btnRun.Click
    ContinueVar = True
    ChooseSaveLocation()
    Case_DatatoGet(DatatoGet:=cmb_DatatoRetrieve.Text)
    If ContinueVar = True Then
        WriteDatatoDestination(datachoice:=cmb_DatatoRetrieve.SelectedItem, 
                                 Destination:=cmb_Destination.SelectedItem)
        Debug.Print("---------------Finished with Run----------------")
    End If

End Sub

Sub Case_DatatoGet(DatatoGet)
    If DatatoGet = "" Then
        MsgBox("Please click on settings and choose data to retrieve")
        ContinueVar = False
    Else
        Select Case DatatoGet
            Case "Company Info"
                GetCompanyInfo(txt_APIUsername.Text, txt_APIPassword.Text)
            Case "Prices"
                GetPrices(txt_APIUsername.Text, txt_APIPassword.Text)
            Case "Balance Sheets"
                Debug.Print("Write a balance sheet sub")
            Case "Income Statements"
                Debug.Print("Write a Income Statement sub")
            Case "Statement of Cash Flows"
                Debug.Print("Write a Statement of Cash Flows sub")
        End Select
    End If

End Sub

这似乎有很多额外的代码来解决一个简单的问题。 有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

如何使用返回值告诉外部函数跳过其他内容?

Sub Outer()
    Inner1()
    If Inner2() = True Then
        Inner3()
    End If

End Sub

Function Inner2() As Boolean
    If condition Is True Then
        Return False
    Else
        dostuff()
        Return True
    End If

End Function