Pergunta

Existe um equivalente VB.NET para o operador ?? 's C #?

Foi útil?

Solução

Use o operador If() com dois argumentos ( Microsoft documentação ):

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

Outras dicas

O operador IF() deve fazer o truque para você:

value = If(nullable, defaultValueIfNull)

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

A resposta aceita não tem qualquer explicação e é simplesmente apenas um link.
Portanto, eu pensei que eu ia deixar uma resposta que explica como o operador If obras retirado MSDN:


Se Operador (Visual Basic)

Usa avaliação curto-circuito para condicionalmente retornar um dos dois valores. O Se operador pode ser chamada com três argumentos ou com dois argumentos.

If( [argument1,] argument2, argument3 )


Se Operador chamado com dois argumentos

O primeiro argumento para Se pode ser omitido. Isto permite que o operador para ser chamado usando apenas dois argumentos. A lista a seguir aplica-se somente quando o Se operador é chamado com dois 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.


Quando o booleano argumento for omitido, o primeiro argumento deve ser uma referência ou tipo nulo. Se o primeiro argumento for avaliado como Nada , o valor do segundo argumento é retornado. Em todos os outros casos, o valor do primeiro argumento é retornado. o seguinte exemplo ilustra como isso funciona avaliação.


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

Um exemplo de como lidar com mais de dois valores (ifs aninhados):

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

Você pode usar um método de extensão. Este funciona como COALESCE SQL e é provavelmente um exagero para o que você está tentando testar, mas 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

dois escolhas anuláveis ??embutidos If(nullable, secondChoice) só pode lidar. Aqui, pode-se Coalesce quantos parâmetros desejado. O primeiro não nulo será devolvido, eo resto dos parâmetros não são avaliadas depois disso (curto-circuito, como AndAlso / && e OrElse / ||)

A única limitação significativa da maioria destas soluções é que eles não vão curto-circuito. Eles, portanto, não são realmente equivalente a ??

A built-in "se" do operador, não vai avaliar os parâmetros subseqüentes a menos que os avalia parâmetros anteriores para nada.

As seguintes declarações são equivalentes.

C #

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

VB

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

Isto irá funcionar em todos os casos em que "??" trabalho. Qualquer uma das outras soluções teriam de ser usado com extrema cautela, pois podem facilmente introduzir erros de tempo de execução.

Verifique a documentação Microsoft sobre Se Operador (Visual Basic) aqui: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator

If( [argument1,] argument2, argument3 )

Aqui estão alguns exemplos (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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top