2012-02-21 74 views
1

有沒有更好的方法來處理嵌套的else if語句有不同的結果?替代嵌套Else如果語句的結果不同?

這裏是我的嵌套語句的一個解釋的例子:

  If My.Computer.Network.Ping(computerName) = True Then 
       Call InstallVS(computerName) 
       If My.Computer.Network.Ping(computerName) = True Then 
        Call PEC(computerName) 
        If My.Computer.Network.Ping(computerName) = True Then 
         Call RemoveSoftware(computerName) 
        Else 
         Call WriteLog(computerName & " lost connectivity while attemping to remove the temp software") 
        End If 
       Else 
        Call WriteLog(computerName & " lost connectivity while Forcing Communication") 
       End If 
      Else 
       Call WriteLog(computerName & " lost connectivity while attemping to Install") 
      End If 

我有很多這些類型的報表的要求,一些比較小的,有些是很多大。

+0

注意,在你的程序中的消息不與在此期間,你失去了連接的動作相對應。它顯示了您想要顯示的動作之後的動作。下面的答案給出了正確的結果,因爲在執行操作之前建立了消息文本,而您的操作在執行後會在 – Martin 2012-02-21 13:58:58

回答

3

您可以創建一個名爲PingOrFail方法,這將考驗連接或以其他方式拋出一個異常,與給定的錯誤消息。那麼你的代碼流可能會是這個樣子:

Try 
    PingOrFail(computerName, "attempting to install") 
    Call InstallVS(computerName) 

    PingOrFail(computerName, "forcing communications") 
    Call PEC(computerName) 

    PingOrFail(computerName, "removing temp software") 
    RemoveSoftware(computerName) 
Catch ex As Exception 
    Call WriteLog (computerName & " lost connectivity while " & ex.Message) 
End Try 

這是PingOrFail方法:

Public Sub PingOrFail(computerName as String, message As String) 
    If My.Computer.Network.Ping(computerName) = False 
     Throw New Exception (message) 
    End If 
End Sub 
+0

謝謝,但是,不會嘗試InstallVS,然後嘗試PEC,無論它是否失敗了上面的? 如果在任何時候ping命令檢查失敗,它需要停止它的操作並退出if語句 – K20GH 2012-02-21 12:02:31

+0

一旦拋出異常(我已經添加了PingOrFail方法以顯示它被拋出的位置),執行將跳到捕獲異常的第一個地方 - 在這種情況下,Catch Ex As Exception語句。在處理之後(使用WriteLog)它將從該點開始繼續 - 它不會返回到拋出異常的地方。 – 2012-02-21 12:07:12

+0

謝謝Avner!我會試一試 – K20GH 2012-02-21 12:08:13

2

這些語句不需要嵌套,如果它們失敗,它們可能會引發異常。

Private Sub DoStuff(ByVal computerName As String) 
    Try 
     If My.Computer.Network.Ping(computerName) Then 
      InstallVS(computerName) 
     Else 
      Throw New Exception(computerName & " lost connectivity while attemping to Install") 
     End If 
     If My.Computer.Network.Ping(computerName) Then 
      PEC(computerName) 
     Else 
      Throw New Exception(computerName & " lost connectivity while Forcing Communication") 
     End If 
     If My.Computer.Network.Ping(computerName) Then 
      RemoveSoftware(computerName) 
     Else 
      Throw New Exception(computerName & " lost connectivity while attemping to remove the temp software") 
     End If 
    Catch ex As Exception 
     WriteLog(ex.Message) 
    End Try 
End Sub 
+0

之後發出異常,是否會退出「循環」? – K20GH 2012-02-21 12:03:40

+2

任何具有「拋出新異常」語句的行都會將其記錄到「Catch ex As Exception」行,並將其記錄到具有WriteLog語句的塊中。 ex.Message將包含你之後的文本。 – 2012-02-21 12:17:42

+0

我不明白爲什麼,但所有的輸出是「Ping請求期間發生的異常」,而不是實際的消息im傳遞 – K20GH 2012-02-21 14:21:00