我正在获取NullReferenceException:
faxnum = Customer.ContactLink.Contact.DefaultFaxLink.Phone.PhoneNumber
null ref在DefaultFaxLink上。由于没有传真号码,DefaultFaxLink未初始化,我知道如果是,我不会在分配时收到错误。
所以,我的问题是,有没有一种方法可以捕获异常而无需测试每个对象以查看它是否无效?
我只想处理一个语句的整个右手部分,这样如果任何部分什么都没有,我只是不给左边的var赋值。
除此之外,我可以在基础对象上使用反射来评估每个成员及其子成员并分配一个空值吗?
答案 0 :(得分: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
答案 1 :(得分: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