VB中的空值检查

78

我想要做的只是检查一个对象是否为null,但是无论我怎么做,如果它能够编译通过,在尝试检查时都会抛出NullReferenceException异常!这是我所做的:

    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


为了在等待答案的同时使事情正常运作,有时可以重构代码使其工作…就像在这种情况下使用一对嵌套 If 语句。 - Sam Axe
2个回答

82

将您的And更改为AndAlso

标准的And将测试两个表达式。如果comp.ContainerNothing,那么第二个表达式会引发NullReferenceException,因为您正在访问空对象的属性。

AndAlso将短路逻辑评估。如果comp.ContainerNothing,则第二个表达式将不会被评估。


42

您的代码比必要的复杂得多。

X IsNot Nothing 替换 (Not (X Is 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

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