【问题标题】:Is there a VB.NET equivalent for C#'s '??' operator?是否有 C# 的 '??' 的 VB.NET 等价物操作员?
【发布时间】:2010-09-29 00:59:37
【问题描述】:

C# 的 ?? 运算符是否有 VB.NET 等效项?

【问题讨论】:

  • 这里的大部分答案(包括接受的答案)都不正确,并且在功能上不等同于 ??在所有情况下。正确的等价物是带有 2 个参数的 if() 语句。然而,第二个参数可以嵌套以获得与 ?? 完全相同的结果。有多个参数。
  • 你的意思是三元运算符吗?:例如return ((value

标签: vb.net operators null-coalescing-operator


【解决方案1】:

使用带有两个参数的If() 运算符 (Microsoft documentation):

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

【讨论】:

  • 我认为VB中的If()语句与C#中的if...?...:相同,而不是??操作符
  • @LukeTO'Brien 如果你使用 3 个参数的话。如果您将其与 2 个参数一起使用,则更多的是 ??(请参阅此问题的另一个答案:stackoverflow.com/a/20686360/1474939)
  • 这个答案展示了如何使用VB If 三个参数。这 not 类似于 C# 的 ?? 运算符。更好的答案是Code Maverick's If with two arguments。 (尼克在几年前也有类似的答案,但不包括 MSDN 的解释。)
  • 这回答了一个完全不同的问题。
  • 要了解以前的cmets,请查看编辑历史。
【解决方案2】:

IF() 运算符应该可以为您解决问题:

value = If(nullable, defaultValueIfNull)

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

【讨论】:

【解决方案3】:

接受的答案没有任何解释,只是一个链接。
因此,我想我会留下一个答案来解释 If 运算符的工作原理,取自 MSDN:


If Operator (Visual Basic)

使用短路评估有条件地返回两个之一 价值观。 If 运算符可以用三个参数或两个参数调用 论据。

If( [argument1,] argument2, argument3 )


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

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


零件

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.


当 Boolean 参数被省略时,第一个参数必须是 引用或可为空的类型。如果第一个参数计算为 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))

如何处理两个以上值的示例(嵌套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)))

【讨论】:

    【解决方案4】:

    您可以使用扩展方法。这一个像 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 任意数量的参数。将返回第一个非空的,之后不评估其余参数(短路,如AndAlso/&amp;&amp; 和OrElse/||)

    【讨论】:

    • 因为该语言有一个内置的运算符。甚至没有理由查看扩展方法。
    • 我不会重复别人的答案。我认为如果您需要使用单个语句检查多个值,提供替代解决方案可能会很好。既然它不是一个错误的答案,那么它应该被否决吗?
    • +1 用于提供使用泛型的实现并避免类型转换/装箱/拆箱
    • @Nick,对不起,但你完全错了。如果您有两个以上的 coalesce 参数,则内置函数不会删除它。
    • 你可以跳过 obj 参数,让 body 为 Return args.FirstOrDefault(Function(arg) arg IsNot Nothing) :-)
    【解决方案5】:

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

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

    以下语句是等价的:

    C#

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

    VB

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

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

    【讨论】:

    • 这在参数数量未知的情况下不起作用(嗯.. 不是不使用 roslyn 或 codedom 来预编译语句以匹配执行时的参数数量)。
    • @StingyJack 这不是故意的。它到底是做什么的??运营商会。
    【解决方案6】:

    在此处查看有关 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"))
    

    【讨论】:

    • 不错!删除评论!
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 2019-02-09
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    相关资源
    最近更新 更多