微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net – VB检查int是否为空

一个非常无聊的问题,对不起,但我真的不知道那个;)我已经尝试过始终string.empty,但是使用小数会产生错误.

有什么功能吗?不幸的是,对于最简单的问题,谷歌没有答案

解决方法

你的标题(和标签)询问“int”,但你的问题是你得到一个带有“十进制”的错误.无论哪种方式,当涉及到 value type(例如整数,十进制等)时,都没有“空”这样的东西.它们不能像 reference type那样设置为nothing(如String或类).相反,值类型具有隐式认构造函数,可自动将该类型的变量初始化为其认值.对于像Integer和Decimal这样的数值,这是0.对于其他类型,请参阅 this table.

因此,您可以使用以下代码检查是否已初始化值类型:

Dim myFavoriteNumber as Integer = 24
If myFavoriteNumber = 0 Then
    ''#This code will obvIoUsly never run,because the value was set to 24
End If

Dim mySecondFavoriteNumber as Integer
If mySecondFavoriteNumber = 0 Then
    MessageBox.Show("You haven't specified a second favorite number!")
End If

请注意,编译器在幕后自动将mySecondFavoriteNumber初始化为0(整数的认值),因此If语句为True.实际上,上面的mySecondFavoriteNumber声明等同于以下语句:

Dim mySecondFavoriteNumber as Integer = 0

当然,正如你可能已经注意到的那样,没有办法知道一个人最喜欢的号码是否真的为0,或者他们是否还没有指定一个喜欢的号码.如果您确实需要一个可以设置为nothing的值类型,则可以使用Nullable(Of T),将变量声明为:

Dim mySecondFavoriteNumber as Nullable(Of Integer)

并检查是否已按如下方式分配:

If mySecondFavoriteNumber.HasValue Then
    ''#A value has been specified,so display it in a message Box
    MessageBox.Show("Your favorite number is: " & mySecondFavoriteNumber.Value)
Else
    ''#No value has been specified,so the Value property is empty
    MessageBox.Show("You haven't specified a second favorite number!")
End If

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐