vb.net - HasValue 给出值 0 而不是 Nothing

标签 vb.net nothing

问题很简单,当我将 Nothing 的 CustomClass 传递到 Query 方法 second.HasValue 最后的 Run 方法时 显示 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

最佳答案

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

在这种情况下,编译器决定 Nothing 表示 Integer 的默认值是 0。为什么?因为他需要找一个implicit conversionId-property,即 Int32

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

Return Query(if(CustomClass IsNot Nothing, CustomClass.Id, New Int32?()))

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

关于vb.net - HasValue 给出值 0 而不是 Nothing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50387614/

相关文章:

vb.net - 如何添加需要 Handles 子句的 WithEvents 变量的定义

null - Webbrowser 控件的 window.external 始终为 null

scala - 在什么条件下推断没有什么可取的?

c# - 从 vb.net 运行的异步任务

c# - 在 .NET 中运行具有重定向文件路径的进程

vb.net - 将 vb6 代码转换为 vb.net?

斯卡拉 : Type Nothing with User defined classes

vb.net - 文本框验证

c# - 将 VB.NET 变量设置为 C# 的 null

Scala:对多态类型的单例实例使用 Nothing