문제

가 VB.NET 해당하는 C#'s ?? operator?

도움이 되었습니까?

해결책

사용 If() 두 가지 인수가있는 운영자 (마이크로 소프트 문서):

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

다른 팁

그만큼 IF() 운영자는 당신을 위해 트릭을 수행해야합니다.

value = If(nullable, defaultValueIfNull)

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

허용 된 답변에는 아무런 설명이 없으며 단순히 링크 일뿐입니다.
그러므로 나는 어떻게 If MSDN에서 가져온 운영자 작업 :


IF 연산자 (Visual Basic)

단락 평가를 사용하여 두 값 중 하나를 조건부로 반환합니다. 그만큼 만약에 연산자는 세 가지 주장이나 두 가지 주장으로 호출 할 수 있습니다.

If( [argument1,] argument2, argument3 )


운영자가 두 가지 인수로 전화 한 경우

첫 번째 논쟁 만약에 생략 할 수 있습니다. 이를 통해 두 개의 인수 만 사용하여 운영자를 호출 할 수 있습니다. 다음 목록은 다음과 같은 경우에만 적용됩니다 만약에 운영자는 두 가지 주장으로 호출됩니다.


부속

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.


부울 인수는 생략되며, 첫 번째 인수는 참조 또는 무효 유형이어야합니다. 첫 번째 인수가 평가되는 경우 아무것도 아님, 두 번째 인수의 값이 반환됩니다. 다른 모든 경우에, 첫 번째 인수의 가치가 반환됩니다. 다음 예는이 평가가 어떻게 작동하는지를 보여줍니다.


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

두 값 이상을 처리하는 방법의 예 (중첩 if에스):

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

할 수 있는 확장자를 사용 방법입니다.이 하나의 작품과 같은 SQL COALESCE 아마 과잉을 위해 당신이 무엇을 테스트하기 위해 노력하고 있지만,그것은 작동합니다.

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

내장 If(nullable, secondChoice) 할 수 있습만을 처리 두 개의 널 선택입니다.여기에,하나는 Coalesce 많은 매개변수를 원하는 대로.Null 이 아닌 첫 번째 하나의 반환될 것,그리고 매개 변수의 나머지 부분에 평가되지 않은 후에는 것(단락,아 AndAlso/&&OrElse/|| )

이러한 솔루션의 대부분의 중요한 한계는 단락하지 않는다는 것입니다. 따라서 그들은 실제로 동등하지 않습니까?

내장 된 "if"연산자는 이전 매개 변수가 아무것도 평가하지 않는 한 후속 매개 변수를 평가하지 않습니다.

다음 진술은 동일합니다.

씨#

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

VB

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

이것은 "?"라는 모든 경우에 작동합니다. 공장. 다른 솔루션 중 하나는 런타임 버그를 쉽게 도입 할 수 있으므로 매우주의해서 사용해야합니다.

IF 운영자 (Visual Basic)에 대한 Microsoft 문서를 확인하십시오. https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator

If( [argument1,] argument2, argument3 )

다음은 몇 가지 예입니다 (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"))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top