HasValue给出值0而不是Nothing

时间:2018-05-17 09:11:59

标签: vb.net nothing

问题很简单,当我在Run方法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 传递给{{1}}方法。不应该是{{1}}吗?

{{1}}

2 个答案:

答案 0 :(得分:4)

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

在这种情况下,编译器决定Nothing表示Integer的默认值为0.为什么?因为他需要找到Id Int32 - Nullable(Of Int32)的属性。

如果您想要Return Query(if(CustomClass IsNot Nothing, CustomClass.Id, New Int32?())) 使用:

null

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

答案 1 :(得分:2)

原因是内联If - 声明。

它会返回Integer而不是Integer?,因为CustomClass.Id显然属于Integer类型。

因此,您可以将CustomClass.Id定义为Integer?,也可以使用CType将其转换为内联Integer?中的If

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