visual operador vb.net operators null-coalescing-operator

visual - ¿Hay un equivalente de VB.NET para C#''s'' ?? '' ¿operador?



+= operador (5)

¿Hay un equivalente de VB.NET para C # ?? ¿operador?



La única limitación significativa de la mayoría de estas soluciones es que no provocarán un cortocircuito. Por lo tanto, ¿no son en realidad equivalentes a?

El operador incorporado "if" no evaluará los parámetros posteriores a menos que el parámetro anterior se evalúe como nada.

Las siguientes declaraciones son equivalentes.

DO#

var value = expression1 ?? expression2 ?? expression3 ?? expression4;

VB

dim value = if(exression1,if(expression2,if(expression3,expression4)))

Esto funcionará en todos los casos donde "??" trabajos. Cualquiera de las otras soluciones debería usarse con extrema precaución, ya que podrían fácilmente introducir errores en tiempo de ejecución.


Puedes usar un método de extensión. Éste funciona como SQL COALESCE y probablemente sea excesivo para lo que intentas probar, pero funciona.

'''''' <summary> '''''' Returns the first non-null T based on a collection of the root object and the args. '''''' </summary> '''''' <param name="obj"></param> '''''' <param name="args"></param> '''''' <returns></returns> '''''' <remarks>Usage '''''' Dim val as String = "MyVal" '''''' Dim result as String = val.Coalesce(String.Empty) '''''' *** returns "MyVal" '''''' '''''' val = Nothing '''''' result = val.Coalesce(String.Empty, "MyVal", "YourVal") '''''' *** returns String.Empty '''''' '''''' </remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function Coalesce(Of T)(ByVal obj As T, ByVal ParamArray args() As T) As T If obj IsNot Nothing Then Return obj End If Dim arg As T For Each arg In args If arg IsNot Nothing Then Return arg End If Next Return Nothing End Function

El If(nullable, secondChoice) incorporado solo puede manejar dos opciones que aceptan nulos. Aquí, uno puede Coalesce tantos parámetros como desee. Se devolverá el primer no nulo, y el resto de los parámetros no se evaluarán después de eso (en cortocircuito, como AndAlso / && y OrElse / || )


el staetement If() . Desde MSDN :

If( [argument1,] argument2, argument3 )

Cuando se llama a If() utilizando tres argumentos, el primer argumento debe evaluarse a un valor que se puede convertir como un booleano. Ese valor booleano determinará cuál de los otros dos argumentos se evalúa y devuelve. La siguiente lista se aplica solo cuando se llama al operador If usando tres argumentos.

...

This statement prints TruePart, because the first argument is true. Console.WriteLine(If(True, "TruePart", "FalsePart")) '' This statement prints FalsePart, because the first argument is false. Console.WriteLine(If(False, "TruePart", "FalsePart")) Dim number = 3 '' With number set to 3, this statement prints Positive. Console.WriteLine(If(number >= 0, "Positive", "Negative")) number = -1 '' With number set to -1, this statement prints Negative. Console.WriteLine(If(number >= 0, "Positive", "Negative"))


La respuesta aceptada no tiene explicación alguna y es simplemente un enlace.
Por lo tanto, pensé que dejaría una respuesta que explica cómo el operador If funciona tomado de MSDN:

MSDN

Utiliza la evaluación de cortocircuito para devolver condicionalmente uno de dos valores. El operador If puede invocarse con tres argumentos o con dos argumentos.

If( [argument1,] argument2, argument3 )


Si el operador llamó con dos argumentos

El primer argumento para If se puede omitir. Esto permite llamar al operador utilizando solo dos argumentos. La siguiente lista se aplica solo cuando se llama al operador If con dos argumentos.


Partes

Term Definition ---- ---------- argument2 Required. Object. Must be a reference or nullable type. Evaluated and returned when it evaluates to anything other than Nothing. argument3 Required. Object. Evaluated and returned if argument2 evaluates to Nothing.


Cuando se omite el argumento booleano , el primer argumento debe ser un tipo de referencia o anulable. Si el primer argumento se evalúa como Nada , se devuelve el valor del segundo argumento. En todos los demás casos, se devuelve el valor del primer argumento. El siguiente ejemplo ilustra cómo funciona esta evaluación.


VB

'' Variable first is a nullable type. Dim first? As Integer = 3 Dim second As Integer = 6 '' Variable first <> Nothing, so its value, 3, is returned. Console.WriteLine(If(first, second)) second = Nothing '' Variable first <> Nothing, so the value of first is returned again. Console.WriteLine(If(first, second)) first = Nothing second = 6 '' Variable first = Nothing, so 6 is returned. Console.WriteLine(If(first, second))

Un ejemplo de cómo manejar más de dos valores (anidados if s):

Dim first? As Integer = Nothing Dim second? As Integer = Nothing Dim third? As Integer = 6 '' The LAST parameter doesn''t have to be nullable. ''Alternative: Dim third As Integer = 6 '' Writes "6", because the first two values are "Nothing". Console.WriteLine(If(first, If(second, third)))