VB 检查整数是否为空

10

非常抱歉,这是一个非常无聊的问题,但我还不知道如何解决;) 我尝试了 always string.empty,但是使用十进制数会产生错误。

是否有任何函数可用?很遗憾,对于最简单的问题,谷歌上没有答案。


(Note: I kept the original HTML tags and only provided the translation.)
3个回答

21
你的标题(和标签)询问关于 "int",但是你的问题说你使用 "decimal" 时遇到了错误。无论如何,对于 值类型(例如 IntegerDecimal 等),都不存在所谓的 "空"。它们不能像 引用类型(如 String 或类)那样被设置为 Nothing。相反,值类型有一个隐式默认构造函数,它会自动将该类型的变量初始化为其默认值。对于像 IntegerDecimal 这样的数值,这个默认值是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

请注意,编译器在幕后自动将mySecondFavoriteNumber初始化为0(Integer的默认值),因此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.Net中,您可以将Nothing分配给值类型。但在这种情况下,Nothing并不意味着“null”,而是“default(T)”,因此对于整数来说,它与0相同。 - jeroenh
@jeroenh:没错。请注意,我说过它们不能像引用类型一样被设置为“Nothing”。将值类型设置为“Nothing”会导致其被初始化回其默认类型。重点是,对于值类型来说,没有这样的“null”或“空”状态;它们始终包含一个值。 - Cody Gray
请注意,最近Dim mySecondFavoriteNumber as Integer?Dim mySecondFavoriteNumber as Nullable(Of Integer)是相同的。 - Mark Schultheiss

3
也许您需要的是Nullable。
    Dim foo As Nullable(Of Integer) = 1
    Dim bar As Nullable(Of Decimal) = 2

    If foo = 1 Then
        If bar = 2 Then
            foo = Nothing
            bar = Nothing
            If foo Is Nothing AndAlso bar Is Nothing Then Stop
        End If
    End If

0

嗯,数字的默认值为0,但您也可以尝试这个:

int x = 123;
String s = "" + x; 

然后检查长度或字符串's'是否为空。


这种方法在 .Net 4.5.2 中不起作用... 未初始化的整数长度为1,需要使用 ToString 转换为字符串。我认为这个答案可能是用 C 写的 :) - seadoggie01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接