2012-02-21 5 views
1

結果が異なるネストされたelse if文を処理する優れた方法はありますか?ここで異なる結果を持つ入れ子のElse If文に代わるものはありますか?

を説明するために私のネストされたステートメントの1の例である:

  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

注プログラムでのメッセージは、あなたが接続を失った時のアクションに対応していないこと。それはあなたが見せたいものに続く行動を示しています。以下の答えは正しい結果をもたらします。なぜなら、あなたが例外をスローした場合、あなたはそれをAFTERWARDS – Martin

答えて

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を試してみませんか? pingチェックが失敗した場合は、何をしてからif文を終了する必要があります。 – K20GH

+0

例外がスローされると(PingOrFailメソッドを追加してスローされた箇所を表示します)、実行はその例外がキャッチされた最初の場所 - この場合はException Exception Catch。それが処理されると(WriteLogを使用して)、その時点以降は続行されます。例外がスローされた位置には戻りません。 –

+0

ありがとうございました!私はそれを行くよ – K20GH

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

+2

"新しい例外をスローする"ステートメントを持つ行は、 "Exatch Ex as Exception"行と、WriteLogステートメントを持つブロックに移動します。 ex.Messageにはあなたの後にあるテキストが含まれます。 –

+0

私は理由を理解することはできませんが、実際のメッセージは – K20GH

関連する問題