2009-02-02 21 views
8

Para las siguientes sentencias If en VB.NET, ¿cuál será la secuencia en la que se evaluarán las condiciones?Evaluación de una instrucción IF en VB.NET

Caso 1:

If (condition1 AND condition2 AND condition3) 
. 
. 
End If 

Caso 2:

If (condition1 OR condition2 OR condition3) 
. 
. 
End If 

Caso 3:

If (condition1 OR condition2 AND condition3 OR condition4) 
. 
. 
End If 

Respuesta

9

VB.NET es una muy extraña bestia desde el punto de vista C-programador. Como se menciona en Gerrie una respuesta diferente, las tres condiciones se evalúan en toda su totalidad, sin cortocircuitos. YAlso y OrElse pueden salvarte el día si eso es lo que quieres.

En cuanto a la última si, el orden de evaluación es el siguiente:

If ((condition1 OR (condition2 AND condition3)) OR condition4) 

Como regla general: si hay cualquier ambiguitiy, utilice paréntesis para especificar el orden de la evaluación de forma explícita.

+1

'Ass Gerrie mencionó ...' –

11

VB.Net evalúa todas las condiciones , entonces el orden no es importante aquí.

Si desea utilizar un cortocircuito, utilizar las palabras clave AndAlso y OrElse.

+0

El orden podría ser teóricamente importante, por ejemplo: si IsStatusOkAndIfNotChangePropertyX (MyObject) o PropertyXHasValueN (MyObject) entonces ... – splattne

+0

Podría ser, pero no sé si puede contar con ello. –

+0

También está la palabra clave 'OrElse' .... –

1

Esto no responde exactamente a la pregunta que nos ocupa, como ya fue respondida, sentí la necesidad de ampliar la palabra clave 'OrElse', mencionada por Anton, así como su relativa: 'Y también', porque alguien aterrizó en esta pregunta, realmente quiero una explicación sobre esto.

'OrElse' and 'AndAlso' Es útil si necesita una evaluación ordenada explícitamente.

A diferencia de 'O' y 'E', si todas las expresiones se evalúan, la instrucción If puede omitir las expresiones restantes si la primera expresión evalúa el valor deseado, cuando utiliza 'OrElse' o 'AndAlso' .

En el siguiente caso, el orden de las expresiones son aplicables a 'OrElse' de izquierda a derecha, sino que además no siempre se evalúan todas las expresiones en función del resultado del valor precedente:

if(Expression1 orelse Expression2 orelse Expression3) 

    ' Code... 

End If 

Si Expression1 es verdadero, luego Expression 2 y 3 son ignorados. Si Expresión1 Si es falso, entonces Expresión2 se evalúa, y luego expresión3 si Expresión2 se evalúa como True.

If (False OrElse True OrElse False) then 
    ' Expression 1 and 2 are evaluated, Expression 3 is ignored. 
End If 

If (True OrElse True OrElse True) then 
    ' only Expression 1 is evaluated. 
End If 

If (True OrElse True OrElse True) then 
    ' only Expression 1 is evaluated. 
End If 

If (False OrElse False OrElse True) then 
    ' All three expressions are evaluated 
End If 

un ejemplo alternativo de la utilización 'OrElse':

If((Object1 is Nothing) OrElse (Object2 is Nothing) OrElse (Object3 is Nothing)) then 


    ' At least one of the 3 objects is not null, but we dont know which one. 
    ' It is possible that all three objects evaluated to null. 
    ' If the first object is null, the remaining objects are not evaluated. 
    ' if Object1 is not NULL and Object2 is null then Object3 is not evaluated 

Else 

    ' None of the objects evaluated to null. 

Endif 

El ejemplo anterior es el mismo que el siguiente:

If(Object1 Is Nothing) 

    ' Object 1 is Nothing 
    Return True 

Else 
    If(Object2 Is Nothing) 
     ' Object 2 is Nothing 
     Return True 
    Else 
     If(Object3 Is Nothing) 
      ' Object 3 is Nothing 
      Return True 
     Else 
      ' One of the objects evaluate to null 
      Return False 
     End If  
    End If  
End If 

También existe la AndAlso palabra clave:

' If the first expression evaluates to false, the remaining two expressions are ignored 
If(Expression1 AndAlso Expression2 AndAlso Expression3) Then ... 

que es utilizable como esto:

If((Not MyObject is Nothing) AndAlso MyObject.Enabled) Then ... 

    ' The above will not evaluate the 'MyObject.Enabled' if 'MyObject is null (Nothing)' 
    ' MyObject.Enabled will ONLY be evaluated if MyObject is not Null. 

    ' If we are here, the object is NOT null, and it's Enabled property evaluated to true 

Else 

    ' If we are here, it is because either the object is null, or it's enabled property evaluated to false; 

End If 

A diferencia de 'Y', como 'Or'- siempre evaluará todas las expresiones:

If((Not MyObject is Nothing) And MyObject.Enabled) Then ... 

    ' MyObject.Enabled will ALWAYS be evaluated, even if MyObject is NULL, 
    ' --- which will cause an Exception to be thrown if MyObject is Null. 

End If 

Pero debido a que el orden puede tener un efecto con 'OrElse' y 'YAdemás', evaluar el clima en que un objeto es nulo debe hacerse primero, como en los ejemplos anteriores.

A continuación se hará una excepción si 'MiObjeto' es nulo

Try 
    If(MyObject.Enabled AndAlso (Not MyObject is Nothing)) Then ... 

     ' This means that first expression MyObject.Enabled Was evaluated to True, 
     ' Second Expression also Evaluated to True 

    Else 

     ' This means MyObject.Enabled evaluated to False, thus also meaning the object is not null. 
     ' Second Expression "Not MyObject is Nothing" was not evaluated. 

    End If 
Catch(e as Exception) 

    ' An exception was caused because we attempted to evaluate MyObject.Enabled while MyObject is Nothing, before evaluating Null check against the object. 

End Try 

satisfaga comentario si he cometido un error o error tipográfico aquí, como he escrito esto a las 5:16 de la mañana después de 2 días sin dormir.

+0

Aterricé aquí y encontré que tu información era muy útil. –

Cuestiones relacionadas