2011-04-07 119 views
45

我想要做的就是檢查一個對象是否爲空,但不管我做什麼,如果它編譯,它會拋出一個NullReferenceException只是試圖檢查!下面是我做了什麼:空值檢查在VB

If ((Not (comp.Container Is Nothing)) And (Not (comp.Container.Components Is Nothing))) Then 
     For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1 
      fixUIIn(comp.Container.Components.Item(i), style) 
     Next 
    End If 

    If ((Not IsDBNull(comp.Container)) And (Not IsDBNull(comp.Container.Components))) Then 
     For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1 
      fixUIIn(comp.Container.Components.Item(i), style) 
     Next 
    End If 

    If ((Not IsNothing(comp.Container)) And (Not IsNothing(comp.Container.Components))) Then 
     For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1 
      fixUIIn(comp.Container.Components.Item(i), style) 
     Next 
    End If 

    If ((Not (comp.Container Is DBNull.Value)) And (Not (comp.Container.Components Is DBNull.Value))) Then 
     For i As Integer = 0 To comp.Container.Components.Count() Step 1 
      fixUIIn(comp.Container.Components.Item(i), style) 
     Next 
    End If 

我已經通過VB的書看了,搜查幾個論壇,並應工作都沒有!對不起,問這樣一個補救問題,但我只需要知道。

只要你知道,調試器說,空對象是comp.Container

+0

得到的東西的工作,你需要等待一個答案,有時事情可重構的工作..喜歡在這種情況下,使用一對嵌套的IFS。 – 2011-04-08 00:25:30

回答

52

更改您的And s到AndAlso小號

標準And將測試兩個表達式。如果comp.Container爲Nothing,那麼第二個表達式將引發NullReferenceException,因爲您正在訪問空對象上的屬性。

AndAlso將短路的邏輯評估。如果comp.Container爲Nothing,則不會評估第二個表達式。

26

您的代碼比必要時混亂得多。

替換(Not (X Is Nothing))X IsNot Nothing與和省略外括號:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then 
    For i As Integer = 0 To comp.Container.Components.Count() - 1 
     fixUIIn(comp.Container.Components(i), style) 
    Next 
End If 

更可讀。 ...另請注意,我已刪除多餘的Step 1和可能多餘的.Item

但是(正如在評論中指出的那樣),基於索引的循環無論如何都是時髦的。除非你絕對必須,否則不要使用它們。使用For Each代替:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then 
    For Each component In comp.Container.Components 
     fixUIIn(component, style) 
    Next 
End If