在VB中空检查

时间:2011-04-07 14:55:04

标签: 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

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

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

2 个答案:

答案 0 :(得分:61)

And更改为AndAlso s

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

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

答案 1 :(得分:31)

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

(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