并且还要避免双重“If-Then”

时间:2015-11-10 15:00:39

标签: vb.net

我想知道我是否可以使用“AndAlso”来避免由对象“无”引起的错误,而不使用双“If-Then” 例如,我有这段代码:

Public Sub Main() Handles Btn_Main.Click
    Dim Word As String = InputBox("Insert a word", "Word", "Word")
    Dim mObject As Object = mWord(Word)
    If Not mObject Is Nothing Then
        If mObject.length >= 6 Then
            MsgBox("The 6th char of the word is " & mObject(6))
        Else
            MsgBox("the word is shorter than 6 characters")
        End If
    End If
End Sub


Function mWord(ByVal Word As String) As Object
    Dim mReturn As Object = Word.tochararray
    If mReturn.length > 6 Then
        Return mReturn
    Else
        Return Nothing
    End If
End Function

我可以通过这种方式避免双重“If-Then”:

Public Sub Main() Handles Btn_Main.Click
    Dim Word As String = InputBox("Insert a word", "Word", "Word")
    Dim mObject As Object = mWord(Word)
    If Not mObject Is Nothing AndAlso mObject.length >= 6 Then
        MsgBox("The 6th char of the word is " & mObject(6))
    Else
        MsgBox("the word is shorter than 6 characters")
    End If
End Sub

这是否也是使用AndAlso的好方法?

1 个答案:

答案 0 :(得分:3)

是的,这是使用AndAlso的好方法,也是运营商的目的。

The visual basic And运算符执行布尔比较,但不会使评估短路。

The visual basic AndAlso运算符执行布尔比较,并使评估短路。

Short circuiting the comparison非常有用,因为它避免了不必要的操作。一般来说,在执行这样的If条件检查时,您希望使用短路布尔运算符。 OrElseAndAlso

的逻辑必然结果

嵌套的If语句,如第一个示例所示,产生重复的代码和更难理解(读取:跟随)逻辑结构。