问题很简单,当我在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}}
答案 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