HasValue 给出值 0 而不是 Nothing

Ari*_*rie 3 vb.net nothing

问题很简单,当我将 CustomClass 传递NothingRun方法的末尾时,Query方法second.HasValue正在显示0。不应该Nothing吗?

Public Function Run() As Boolean
       Return Query(if(CustomClass IsNot Nothing, CustomClass.Id, Nothing))
End Function

Public Function Query(second As Integer?) As Boolean
    ...
    If second.HasValue Then
        'value = 0 !
        Else
           'some query
        End If

    ...
End Function
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 5

这是 VB.NET 的一个奇怪之处。Nothing不仅意味着null(C#)还意味着default(C#)。所以它将返回给定类型的默认值。出于这个原因,您甚至可以分配Nothing给一个Integer变量(或任何其他引用或值类型)。

在这种情况下,编译器决定这Nothing意味着默认值为Integer0。为什么?因为他需要找到对- 属性的隐式转换Id,即Int32.

如果你想Nullable(Of Int32)使用:

Return Query(if(CustomClass IsNot Nothing, CustomClass.Id, New Int32?()))
Run Code Online (Sandbox Code Playgroud)

因为我提到了 C#,如果你在那里尝试同样的,你会得到一个编译器错误,在null和之间没有隐式转换int。在 VB.NET 中有一个,默认值为 0。