2010-11-22 59 views
8

一個非常無聊的問題,很抱歉,但我真的不知道那個;)我總是嘗試string.empty,但用小數點會產生一個錯誤。VB檢查int是否爲空

有沒有什麼功能?不幸的是,最簡單的問題,也有對谷歌沒有答案

回答

15

你的標題(和標籤)問一個「int」,但你的問題說你得到一個「十進制」的錯誤。無論哪種方式,當涉及到value type(例如IntegerDecimal等)時,不存在「空」這樣的事物。他們不能設置爲Nothing,因爲您可以使用reference type(如String或類)。相反,值類型具有隱式默認構造函數,可以自動將該類型的變量初始化爲其默認值。對於IntegerDecimal等數字值,該值爲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(對於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 
+0

只是一個側面說明:其實你可以* *分配沒什麼值類型在VB.Net。但在這種情況下,Nothing並不意味着'null',而是'default(T)',因此整數與0相同。 – jeroenh 2010-11-22 23:40:51

+0

@jeroenh:這是正確的。請注意,我說他們不能像引用類型*那樣設置爲「Nothing」。將值類型設置爲Nothing,將使其初始化爲其默認類型。重點是值類型不存在這種「空」或「空」狀態;它們總是包含一個值。 – 2010-11-23 00:52:51

+0

最近注意,'Dim mySecondFavoriteNumber as Integer?'與Dim mySecondFavoriteNumber與Nullable(Of Integer)相同' – 2013-09-06 13:31:29

0

那麼,對於一些默認值是0,但你也可以試試這個:

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

,然後檢查長度,或者字符串's'是空的。

2

也許你正在尋找的是可空

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