2012-02-21 89 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