Domanda

Esiste un equivalente VB.NET per l'operatore ?? di C #?

È stato utile?

Soluzione

Utilizza l'operatore If () con due argomenti ( documentazione 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))

Altri suggerimenti

L'operatore IF () dovrebbe fare il trucco per te:

value = If(nullable, defaultValueIfNull)

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

La risposta accettata non ha alcuna spiegazione ed è semplicemente un link.
Pertanto, ho pensato di lasciare una risposta che spiegasse come funziona l'operatore If preso da MSDN:


Se operatore (Visual Basic)

  

Utilizza la valutazione del corto circuito per restituire condizionalmente uno dei due   valori. L'operatore Se può essere chiamato con tre argomenti o con due   argomenti.

     
If( [argument1,] argument2, argument3 )

Se l'operatore ha chiamato con due argomenti

  

Il primo argomento di Se può essere omesso. Ciò consente all'operatore   da chiamare usando solo due argomenti. Si applica il seguente elenco   solo quando l'operatore Se viene chiamato con due argomenti.

Parts

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.

  

Quando l'argomento Booleano viene omesso, il primo argomento deve essere a   tipo di riferimento o nullable. Se il primo argomento valuta    Niente , viene restituito il valore del secondo argomento. In tutti gli altri casi, viene restituito il valore del primo argomento. Il   l'esempio seguente mostra come funziona questa valutazione.

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 esempio di come gestire più di due valori ( nidificato se 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)))

Puoi usare un metodo di estensione. Questo funziona come SQL COALESCE ed è probabilmente eccessivo per quello che stai cercando di testare, ma funziona.

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

Il If (nullable, secondChoice) integrato può gestire solo due scelte nullable. Qui, si può Coalesce quanti parametri si desidera. Verrà restituito il primo non null e il resto dei parametri non verrà valutato successivamente (in cortocircuito, come AndAlso / & amp; & amp; e OrElse / || )

L'unico limite significativo della maggior parte di queste soluzioni è che non cortocircuiteranno. Pertanto non sono effettivamente equivalenti a ??

Il " if " integrato operatore, non valuterà i parametri successivi a meno che il parametro precedente non valuti nulla.

Le seguenti dichiarazioni sono equivalenti.

C #

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

VB

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

Funzionerà in tutti i casi in cui " ?? " lavori. Qualsiasi altra soluzione dovrebbe essere utilizzata con estrema cautela, in quanto potrebbe facilmente introdurre bug di runtime.

Controlla la documentazione Microsoft su If Operator (Visual Basic) qui: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator

If( [argument1,] argument2, argument3 )

Ecco alcuni esempi (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"))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top