是否可以在VB.NET中使用具有可空值的Select Case?

Hei*_*nzi 10 vb.net

以下代码

Sub Foo(i As Int32?)
    Select Case i
        Case Nothing              ' <-- warning here
            ' Do something
        Case 0
            ' Do something else
        Case Else
            ' Do something different
    End Select
End Sub
Run Code Online (Sandbox Code Playgroud)

产生以下警告:

警告BC42037:此表达式将始终计算为Nothing(由于来自equals运算符的空传播).要检查值是否为null,请考虑使用"Is Nothing".

Case Is Nothing但是,会产生语法错误:

错误BC30239:期望关系运算符.

有没有办法使用Select Case可以为空的值类型和案例的case子句Nothing

Fab*_*bio 2

只是解决方法

Sub Foo(i As Int32?)
    Dim value = i.GetValueOrDefault(Integer.MinValue)
    Select Case value 
        Case Integer.MinValue ' is Nothing
            ' Do something
        Case 0
            ' Do something else
        Case Else
            ' Do something different
    End Select
End Sub
Run Code Online (Sandbox Code Playgroud)

另一种解决方法可以是

Sub Foo(i As Integer?)
    If i.HasValue = False Then 
        ExecuteIfNoValue()
        Exit Sub
    End If

    Select Case i.Value
        Case 0
            ' Execute if 0
        Case Else
            ' Execute something else
    End Select
End Function
Run Code Online (Sandbox Code Playgroud)

在 C# 7switch语句中已经接受其他原始类型,并且可以使用 nullable。
因此,您可以仅为此方法创建 C# 项目并使用 C# 7 的新功能:)

void Foo(int? i)
{
    switch(i)
    {
        case null:
            // ExecuteIfNoValue();
            break;
        case 0:
            // ExecuteIfZero();
            break;
        default:
            // ExecuteIfDefault();          
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个有效的解决方法,但使用幻数有点违背了拥有可为空值的目的。 (3认同)