Pregunta

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

¿Fue útil?

Solución

Use el operador If () con dos argumentos ( documentación de Microsoft ):

' 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))

Otros consejos

El operador IF () debería hacer el truco por ti:

value = If(nullable, defaultValueIfNull)

http://visualstudiomagazine.com/listings/list.aspx?id=252

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


If Operator (Visual Basic)

  

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

     
If( [argument1,] argument2, argument3 )


Si el operador llamó con dos argumentos

  

El primer argumento de Si se puede omitir. Esto permite al operador   para ser llamado usando solo dos argumentos. Se aplica la siguiente lista   solo cuando se llama al operador Si 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   Referencia o tipo nullable. Si el primer argumento evalúa a    Nada , se devuelve el valor del segundo argumento. En todos los demás casos, se devuelve el valor del primer argumento. los   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 (anidado si 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)))

Puedes usar un método de extensión. Este funciona como SQL COALESCE y probablemente sea excesivo para lo que está intentando 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 incorporado Si (con posibilidad de nulos, secondChoice) solo puede manejar dos opciones que aceptan nulos. Aquí, uno puede Coalesce tantos parámetros como se desee. Se devolverá el primero que no sea nulo, y el resto de los parámetros no se evaluarán después de eso (cortocircuitado, como AndAlso / & amp; & amp; y OrElse / || )

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

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

Las siguientes declaraciones son equivalentes.

C #

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 tendría que usarse con extrema precaución, ya que podrían introducir errores en tiempo de ejecución.

Consulte la documentación de Microsoft sobre el operador If (Visual Basic) aquí: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator

If( [argument1,] argument2, argument3 )

Aquí hay algunos ejemplos (VB.Net)

' 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"))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top