1

我倾向于使用

If Not IsDBNull(dr("data")) Then
     myData = dr("data")
End If

捕捉空值。有没有更好的办法?看来我一遍又一遍地使用它?任何人都编写一个函数来检查这个类似的东西

mydata = IfNotNull("data")

我不知道如何处理可能返回的不同数据类型。感谢您的任何想法!

4

1 回答 1

4

在我的 CLR 对象为 Nullable 的情况下,当我使用 VB.NET 时,我使用了这个扩展方法:

    Private Function GetNullable(Of T As Structure)(ByVal row As System.Data.DataRow, ByVal fieldname As String, ByVal convert As Conversion(Of T)) As Nullable(Of T)
        Dim nullable As Nullable(Of T)
        If System.Convert.IsDBNull(row(fieldname)) Then
            nullable = Nothing
        Else
            nullable = convert(row, fieldname)
        End If
        Return nullable
    End Function

与以下代表Conversion(Of T)

Private Delegate Function Conversion(Of T)(ByVal row As System.Data.DataRow, ByVal fieldname As String) As T

然后,我对相关数据类型的扩展进行分层:

    <Extension()> _
    Public Function GetDouble(ByVal row As System.Data.DataRow, ByVal name As String) As Double
        Return Convert.ToDouble(row(name))
    End Function

    <Extension()> _
    Public Function GetNullableDouble(ByVal row As System.Data.DataRow, ByVal name As String) As System.Nullable(Of Double)
        Return GetNullable(Of Double)(row, name, AddressOf GetDouble)
    End Function

最后,我可以使用:

Dim amount As Double? = dr.GetNullableDouble("amount")
于 2010-09-07T18:31:28.027 回答