2010-10-27 55 views
0

我有这样的方法:在VB.NET法“一无所有”准备

Private Sub SetIfNotNull(ByVal input As Object, ByRef destination As Object, ByVal ConversionType As ConversionType) 
     If input IsNot Nothing AndAlso input <> "" Then 
      Select Case ConversionType 
       Case DealerTrackConnection.ConversionType._String 
        destination = input 
       Case DealerTrackConnection.ConversionType._Integer 
        destination = Convert.ToInt32(input) 
       Case DealerTrackConnection.ConversionType._Double 
        destination = Convert.ToDouble(input) 
       Case DealerTrackConnection.ConversionType._Date 
        destination = Convert.ToDateTime(input) 
       Case DealerTrackConnection.ConversionType._Decimal 
        destination = Convert.ToDecimal(input) 
      End Select 
     End If 
    End Sub 

这里是一个呼叫中失败:

SetIfNotNull(ApplicantElement.Element("suffix").Value, NewApplicant.Suffix, ConversionType._String) 

如果从XML文件中的元素是没有(没有标签),方法调用失败。但我没有检查什么。为什么要这样做,以及如何修改代码以在这个时间和每次都修复它。

回答

2

的问题是不是在你的SetIfNotNull方法,而正是在这一段代码:ApplicantElement.Element("suffix").Value

元素是空的,所以Value调用抛出一个NullReferenceException。试试这个:

CType(ApplicantElement.Element("suffix"), String) 

此外,您还可以巩固检查这一行:

If input IsNot Nothing AndAlso input <> "" Then 

到这一点:

If Not String.IsNullOrEmpty(input) Then 
+0

+1这些检查可以进一步合并。在VB.Net中,'String.IsNullOrEmpty(input)'等价于'(input =“”)',因为VB.Net在使用'='进行字符串比较时将''''看作''“''。 [见这里](http://stackoverflow.com/questions/2633166/nothing-string-empty-why-are-these-equal/2633274#2633274) – MarkJ 2010-10-28 08:27:39

+0

@MarkJ谢谢,我没有意识到这一点:) – 2010-10-28 15:38:51

0

似乎ApplicantElement.Element( “后缀”)什么也没有,因此在你的方法被调用之前发生异常,不是吗?

If Not ApplicantElement.Element("suffix") Is Nothing Then 
    SetIfNotNull(ApplicantElement.Element("suffix").Value, NewApplicant.Suffix, ConversionType._String) 
End If