确定特定的可空类型

时间:2015-11-16 17:53:50

标签: .net vb.net reflection nullable

我有一个函数,对于给定的对象循环其属性(几种数据类型),但是当我添加一个类型 SqlDateTime?时,我得到一个无效的强制转换异常。这是部分

    Dim cad As SqlString? =  prop.GetValue(obj)

它失败了,因为在过去唯一可以为空的类型是SqlString ?,所以我想知道我正在处理的特定类型的可空(SqlString?,SqlDateTime?等)。

完整代码

Class staticx

    Public Property name As SqlString
    Public Property address As sqlString?
    Public Property dateAdded As SqlDateTime?

    Public Shared Sub check(obj As staticx)
        For Each prop As System.Reflection.PropertyInfo In GetType(staticx).GetProperties
            If Nullable.GetUnderlyingType(prop.PropertyType) <> Nothing Then
               Dim cad As SqlString? =  prop.GetValue(obj)
            End If
    End Sub

End Class

调用它

 Dim wayne As New staticx With {.name= "jhon", .address= "ape", .dateAdded= Date.Today}
 staticx.check(wayne)

1 个答案:

答案 0 :(得分:1)

要测试特定类型(例如SqlString?SqlDateTime?),您可以使用TypeOf运算符,例如:

If Nullable.GetUnderlyingType(prop.PropertyType) <> Nothing Then
    If TypeOf prop.GetValue(obj) Is SqlString? Then
        ' Dim cad As SqlString? ...
    ElseIf TypeOf prop.GetValue(obj) Is SqlDateTime? Then
        ' Dim cad As SqlDateTime? ...
    Else
        ' Found another kind of Nullable type!
    End If
...

显然,面对新的可空类型,这种方法不能很好地扩展,但是如果你觉得不会有很多其他可空类型(或者如果你只是感兴趣的话)在处理这些特定的2个可空类型时,这可能是一种可行的方法。