替代嵌套的Else If具有不同结果的语句?

时间:2012-02-21 11:01:20

标签: vb.net

对于具有不同结果的语句,是否有更好的方法来处理嵌套的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

我需要大量这些类型的语句,有些是较小的,有些则要大得多。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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