2011-04-07 120 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