2011-04-07 3 views
45

내가하고 싶은 것은 객체가 null인지 확인하는 것입니다.하지만 컴파일 할 때 확인을 시도하는 것은 NullReferenceException입니다. 여기에 내가 무슨 짓을했는지의 :null 체크 VB에서

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 책을보고 여러 포럼을 검색하고 작업을해야 모든 것을하지 않는 것! 그러한 구제 적 질문을하는 것에 대해 유감스럽게 생각합니다. 그러나 나는 단지 알 필요가 있습니다. 그냥 알다시피

는, 디버거는 널 객체가 AndAlso

표준 And-comp.Container

+0

당신이 대답을 기다리는 동안 일하는 것을 얻기 위해, 때로는 사물이 경우 중첩 된 Ifs의 한 쌍을 사용하여 같은 .. 일을 리팩토링 할 수있다. –

답변

52

변경하여 And들 두 표현식을 테스트라고 말했다. comp.Container가 Nothing이면 null 객체의 속성에 액세스하기 때문에 두 번째 표현식이 NullReferenceException을 발생시킵니다.

AndAlso 논리적 평가가 단락됩니다. comp.Container가 Nothing이면 두 번째 표현식이 평가되지 않습니다.

26

코드가 필요 이상으로 혼란 스럽습니다.

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