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

前端之家收集整理的这篇文章主要介绍了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

猜你在找的VB相关文章