VB.NET中,使用HasValue时为何返回0而非Nothing?

2026-05-08 13:063阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计301个文字,预计阅读时间需要2分钟。

VB.NET中,使用HasValue时为何返回0而非Nothing?

问题很简单,当我查询方法中遇到`second.HasValue`显示0时,将最后一行的`CustomClass`传递给`Run`方法。这应该不是什么问题。

csharpPublic Function Run() As Boolean Return Query(if(CustomClass IsNot Nothing, CustomClass.Id, Nothing))End Function

问题很简单,当我在查询方法second.HasValue显示0时,将最后一行的CustomClass传递给Run方法.应该不是什么?

VB.NET中,使用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 这是一个VB.NET的怪异. Nothing不仅意味着 null(C#)而且意味着 default(C#).因此它将返回给定类型的默认值.由于这个原因,您甚至可以将Nothing赋值给Integer变量(或任何其他引用或值类型).

在这种情况下,编译器决定Nothing意味着Integer的默认值为0.为什么?因为他需要找到属于Int32属性的implicit conversion.

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

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

因为我提到了C#,如果你在那里尝试相同,你将得到一个编译器错误,即null和int之间没有隐式转换.在VB.NET中有一个,默认值为0.

本文共计301个文字,预计阅读时间需要2分钟。

VB.NET中,使用HasValue时为何返回0而非Nothing?

问题很简单,当我查询方法中遇到`second.HasValue`显示0时,将最后一行的`CustomClass`传递给`Run`方法。这应该不是什么问题。

csharpPublic Function Run() As Boolean Return Query(if(CustomClass IsNot Nothing, CustomClass.Id, Nothing))End Function

问题很简单,当我在查询方法second.HasValue显示0时,将最后一行的CustomClass传递给Run方法.应该不是什么?

VB.NET中,使用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 这是一个VB.NET的怪异. Nothing不仅意味着 null(C#)而且意味着 default(C#).因此它将返回给定类型的默认值.由于这个原因,您甚至可以将Nothing赋值给Integer变量(或任何其他引用或值类型).

在这种情况下,编译器决定Nothing意味着Integer的默认值为0.为什么?因为他需要找到属于Int32属性的implicit conversion.

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

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

因为我提到了C#,如果你在那里尝试相同,你将得到一个编译器错误,即null和int之间没有隐式转换.在VB.NET中有一个,默认值为0.