在VB中空检查


70

我要做的就是检查对象是否为空,但是不管我做什么,如果它编译了,它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书籍,搜索了多个论坛,所有应该工作的内容都不起作用!很抱歉提出这样的补救性问题,但我只需要知道。

大家知道,调试器说null对象是 comp.Container


为了让事情在等待答案的同时工作,有时事情可以重构为工作。例如在这种情况下使用一对嵌套的If。
山姆Ax

Answers:


74

Ands更改为AndAlsos

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

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


34

您的代码比必要的更加混乱。

替换(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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.