VB检查int是否为空

Flo*_*ler 8 vb.net integer value-type

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

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

Cod*_*ray 18

你的标题(和标签)询问"int",但你的问题是你得到一个带有"十进制"的错误.无论哪种方式,有没有这样的事情"空",当它涉及到一个值类型(如Integer,Decimal等).他们不能被设置Nothing为你可以用引用类型(如String或类).相反,值类型具有隐式默认构造函数,可自动将该类型的变量初始化为其默认值.对于像Integer和的数值Decimal,这是0.对于其他类型,请参阅此表.

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

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
Run Code Online (Sandbox Code Playgroud)

注意,编译器在幕后mySecondFavoriteNumber自动初始化为0(默认值为a Integer),因此If语句为True.事实上,上述声明mySecondFavoriteNumber等同于以下声明:

Dim mySecondFavoriteNumber as Integer = 0
Run Code Online (Sandbox Code Playgroud)


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

Dim mySecondFavoriteNumber as Nullable(Of Integer)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)