C# 的 '??' 是否有 VB.NET 等价物?操作员?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/403445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:59:59  来源:igfitidea点击:

Is there a VB.NET equivalent for C#'s '??' operator?

vb.netoperatorsnull-coalescing-operator

提问by Nathan Koop

Is there a VB.NET equivalent for C#'s ??operator?

C# 的??运算符是否有 VB.NET 等价物?

采纳答案by Firas Assaad

Use the If()operator with two arguments (Microsoft documentation):

使用If()带有两个参数的运算符(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))

回答by Nick

The IF()operator should do the trick for you:

IF()运营商应该为你做的伎俩:

value = If(nullable, defaultValueIfNull)

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

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

回答by Code Maverick

The accepted answer doesn't have any explanation whatsoever and is simply just a link.
Therefore, I thought I'd leave an answer that explains how the Ifoperator works taken from MSDN:

接受的答案没有任何解释,只是一个链接。
因此,我想我会If从 MSDN 中留下一个解释操作员如何工作的答案:



If Operator (Visual Basic)

If 运算符 (Visual Basic)

Uses short-circuit evaluation to conditionally return one of two values. The Ifoperator can be called with three arguments or with two arguments.

If( [argument1,] argument2, argument3 )

使用短路评估有条件地返回两个值之一。该如果操作员可以用三个参数或两个参数来调用。

If( [argument1,] argument2, argument3 )



If Operator Called with Two Arguments

如果使用两个参数调用运算符

The first argument to Ifcan be omitted. This enables the operator to be called by using only two arguments. The following list applies only when the Ifoperator is called with two arguments.

If的第一个参数可以省略。这使得可以仅使用两个参数来调用运算符。以下列表仅适用于使用两个参数调用If运算符时。



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.



When the Booleanargument is omitted, the first argument must be a reference or nullable type. If the first argument evaluates to Nothing, the value of the second argument is returned. In all other cases, the value of the first argument is returned. The following example illustrates how this evaluation works.

当省略布尔参数时,第一个参数必须是引用或可为空类型。如果第一个参数的计算结果为 Nothing,则返回第二个参数的值。在所有其他情况下,返回第一个参数的值。以下示例说明了此评估的工作原理。



VB

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

An example of how to handle more than two values (nested ifs):

如何处理两个以上的值(嵌套ifs)的示例:

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

回答by StingyHyman

You can use an extension method. This one works like SQL COALESCEand is probably overkill for what you are trying to test, but it works.

您可以使用扩展方法。这个像 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

The built-in If(nullable, secondChoice)can only handle twonullable choices. Here, one can Coalesceas many parameters as desired. The first non-null one will be returned, and the rest of the parameters are not evaluated after that (short circuited, like AndAlso/&&and OrElse/||)

内置If(nullable, secondChoice)只能处理两个可为空的选择。在这里,您可以Coalesce根据需要设置任意数量的参数。将返回第一个非空的,之后不评估其余参数(短路,如AndAlso/&&OrElse/ ||

回答by user1751825

The one significant limitation of most of these solutions is that they won't short-circuit. They are therefore not actually equivalent to ??.

大多数这些解决方案的一个重要限制是它们不会短路。因此,它们实际上并不等同于??

The built-in Ifoperator won't evaluate subsequent parameters unless the earlier parameter evaluates to nothing.

If除非前面的参数计算结果为零,否则内置运算符不会计算后续参数。

The following statements are equivalent:

以下语句是等效的:

C#

C#

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

VB

VB

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

This will work in all cases where ??works. Any of the other solutions would have to be used with extreme caution, as they could easily introduce run-time bugs.

这将适用于所有有效的情况??。任何其他解决方案都必须非常谨慎地使用,因为它们很容易引入运行时错误。

回答by FN90

Check Microsoft documentation about If Operator (Visual Basic) here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator

在此处查看有关 If Operator (Visual Basic) 的 Microsoft 文档:https: //docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator

If( [argument1,] argument2, argument3 )

Here are some examples (VB.Net)

这里有一些例子(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"))