vb.net – HasValue给出值0而不是Nothing
发布时间:2020-12-17 07:29:27 所属栏目:百科 来源:网络整理
导读:问题很简单,当我在查询方法second.HasValue显示0时,将最后一行的CustomClass传递给Run方法.应该不是什么? Public Function Run() As Boolean Return Query(if(CustomClass IsNot Nothing,CustomClass.Id,Nothing))End FunctionPublic Function Query(second
问题很简单,当我在查询方法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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |