问题很简单,当我在查询方法second.HasValue显示0时,将最后一行的CustomClass传递给Run方法.应该不是什么?
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
解决方法
这是一个VB.NET的怪异.
Nothing
不仅意味着
null
(C#)而且意味着
default
(C#).因此它将返回给定类型的默认值.由于这个原因,您甚至可以将Nothing赋值给Integer变量(或任何其他引用或值类型).
在这种情况下,编译器决定Nothing意味着Integer的默认值为0.为什么?因为他需要找到属于Int32属性的implicit conversion.
如果你想要一个Nullable(Of Int32)使用:
Return Query(if(CustomClass IsNot Nothing,New Int32?()))
因为我提到了C#,如果你在那里尝试相同,你将得到一个编译器错误,即null和int之间没有隐式转换.在VB.NET中有一个,默认值为0.