vb.net – 空检查VB

所有我想做的是检查一个对象是否为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书,搜索几个论坛,和一切应该工作不是!对不起,问这样的补救问题,但我只是需要知道。

只是这样你知道,调试器说,null对象是comp.Container

改变你的Ands到AndAlsos

A标准并将测试这两个表达式。如果comp.Container是Nothing,那么第二个表达式将引发一个NullReferenceException,因为你正在访问一个null对象的属性。

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

http://stackoverflow.com/questions/5583112/null-check-in-vb

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:vb.net – 空检查VB