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

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...