识别特定的可空类型
Identify specific nullable type
我有一个针对给定对象循环遍历其属性(多种数据类型)的函数,但是当我添加一个类型为 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)
要测试特定类型(例如 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
...
显然,面对新的可空类型,这种方法无法很好地扩展,但如果您认为不会有很多其他可空类型(或者如果您只对处理这两种特定的可空类型感兴趣),那么这可能是一种可行的方法。
我有一个针对给定对象循环遍历其属性(多种数据类型)的函数,但是当我添加一个类型为 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)
要测试特定类型(例如 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
...
显然,面对新的可空类型,这种方法无法很好地扩展,但如果您认为不会有很多其他可空类型(或者如果您只对处理这两种特定的可空类型感兴趣),那么这可能是一种可行的方法。