在VB中空检查

Sup*_*tar 65 vb.net null runtime-error

我想做的就是检查一个对象是否为空,但无论我做什么,如果它编译,它会抛出一个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
Run Code Online (Sandbox Code Playgroud)

我查看了VB书籍,搜索了几个论坛,而且应该工作的一切都没有!很抱歉提出这样一个补救问题,但我只需要知道.

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

Ken*_*isa 68

将你的Ands改为AndAlsos

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

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


Kon*_*lph 32

你的代码比必要的更混乱.

更换(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
Run Code Online (Sandbox Code Playgroud)

更具可读性....还要注意我已经删除了冗余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
Run Code Online (Sandbox Code Playgroud)