我有一个函数,对于给定的对象,它通过(几个数据类型的)属性循环,但当我添加一个类型为SqlDateTime的函数时我得到一个无效的强制转换异常。这是
Dim cad As SqlString? = prop.GetValue(obj)
它失败了,因为在过去,唯一可以为null的类型是SqlString?,所以我想知道我正在处理的可为null的特定类型(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)
要测试特定类型(例如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
...
显然,面对新类型的可为null的类型,这种方法不能很好地扩展,但如果你确信不会有很多其他可为null类型(或者如果你只对处理这两种特定的可为nullable类型感兴趣),那么这可能是一种可行的方法。