2012-06-27 21 views
0

我在得到的NullReferenceException:測試對象白白和反思

faxnum = Customer.ContactLink.Contact.DefaultFaxLink.Phone.PhoneNumber

空裁判是在DefaultFaxLink。由於沒有傳真號碼,因此DefaultFaxLink未初始化,我知道如果是這樣,我不會在賦值時得到錯誤。

所以,我的問題是,有沒有一種方法可以捕獲異常,而不必測試每個對象,看看它是什麼?

我只是想對待語句的整個右手部分,以便如果任何部分是什麼都沒有,我只是沒有分配任何東西到左var。

簡而言之,我可以在基礎對象上使用反射來評估每個成員及其子成員並分配一個空值嗎?

回答

0

寫一個函數。

Public Class Customer 

    Public Function GetFaxNumberSafe() As String 

     If Me.ContactLink IsNot Nothing AndAlso 
      Me.ContactLink.Contact IsNot Nothing AndAlso 
      Me.ContactLink.Contact.DefaultFaxLink IsNot Nothing AndAlso 
      Me.ContactLink.Contact.DefaultFaxLink.Phone IsNot Nothing Then 

      Return Customer.ContactLink.Contact.DefaultFaxLink.Phone.PhoneNumber 

     Else 

      Return Nothing 

     End If 

    End Function 

End Class 

你也可以設置你的對象延遲加載實例化訪問,所以你總是有一個對象引用。

Public Class Customer 

    Private _contactLink As New Lazy(Of ContactLink)() 

    Public ReadOnly Property ContactLink As ContactLink 
     Get 
      Return _contactLink.Value 
     End Get 
    End Property 

End Class 
+0

我知道的多,如果對每個成員,並在try-catch。我試圖不必這樣做,因爲我需要在多個領域做到這一點。有沒有辦法像'C'語言一樣創建宏(像#define)來包裝語句? – user901160

+0

捕獲異常並不是一個好的解決方案,因爲您不一定會知道爲什麼引發異常。我認爲你正試圖爲解決方案簡單的問題找到一個過於聰明的解決方案。任何「聰明」的解決方案都會增加額外的開銷或代碼複雜性,這是不必要的。如果您的目標僅僅是確保這些對象始終存在,那麼只需創建對象即可。懶惰實例化它們,或者在每個類的構造函數中創建它們。 – ulty4life

+0

嗯,你說陷阱的例外不是一個好的解決方案,因爲你不知道爲什麼它被拋出然而在你的函數解決方案中,你仍然不知道哪個屬性是空的,所以我相信它們一樣糟糕 – goughy000

1

你可以使用一個try-catch塊的NullReferenceException

Public Class Customer 
    Public ContactLink As ContactLink 
End Class 

Public Class ContactLink 
    Public Contact As Contact 
End Class 

Public Class Contact 
    Public DefaultFaxLink As FaxLink 
End Class 

Public Class FaxLink 
    Public Phone As Phone 
End Class 

Public Class Phone 
    Public PhoneNumber As String 
End Class 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

    Dim objCustomer As New Customer 
    objCustomer.ContactLink = New ContactLink 
    objCustomer.ContactLink.Contact = New Contact 
    objCustomer.ContactLink.Contact.DefaultFaxLink = New FaxLink 

    Dim PhoneNumber As String = "" 

    Try 
     PhoneNumber = objCustomer.ContactLink.Contact.DefaultFaxLink.Phone.PhoneNumber 
    Catch ex As NullReferenceException 
     PhoneNumber = "" 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 

    If Not String.IsNullOrEmpty(PhoneNumber) Then 
     MsgBox("Fax number is..." & PhoneNumber) 
    Else 
     MsgBox("No fax number!") 
    End If 

End Sub