Vb.net 如何通过反射对对象的可空属性调用HasValue?
此函数循环对象的所有属性,以创建updatequery以将te对象保存到DB 由于引入了可空属性,我们不得不对其进行一些更改。 如果该属性可为null,我们希望检查“HasValue”属性。 当它有一个值时,它确实起作用。当属性没有值时,我们会在CBool行得到一个“非静态方法需要一个目标”-错误 有什么建议吗? 使用反射检查属性的“HasValue”属性的另一种方法 谢谢Vb.net 如何通过反射对对象的可空属性调用HasValue?,vb.net,reflection,nullable,Vb.net,Reflection,Nullable,此函数循环对象的所有属性,以创建updatequery以将te对象保存到DB 由于引入了可空属性,我们不得不对其进行一些更改。 如果该属性可为null,我们希望检查“HasValue”属性。 当它有一个值时,它确实起作用。当属性没有值时,我们会在CBool行得到一个“非静态方法需要一个目标”-错误 有什么建议吗? 使用反射检查属性的“HasValue”属性的另一种方法 谢谢 Private Function GetUpdateQuery(ByVal obj As Object, ByRef p
Private Function GetUpdateQuery(ByVal obj As Object, ByRef params As List(Of SqlParameter), Optional ByVal excl As String() = Nothing) As String
Dim sql As String = String.Empty
Dim props As PropertyInfo() = obj.GetType().GetProperties
If excl Is Nothing Then
excl = New String() {}
End If
For Each prop As PropertyInfo In props
Try
If Not excl.Contains(prop.Name) And prop.CanWrite = True Then
sql &= String.Format("{0} = @{1},", prop.Name, prop.Name)
Dim param As SqlParameter
Dim value As Object
If prop.PropertyType.IsGenericType AndAlso prop.PropertyType.GetGenericTypeDefinition() = GetType(Nullable(Of )) Then
If CBool(prop.PropertyType.GetProperty("HasValue").GetValue(prop.GetValue(obj, Nothing), Nothing)) Then
value = prop.GetValue(obj, Nothing)
Else
value = DBNull.Value
End If
Else
If prop.GetValue(obj, Nothing) = Nothing Then
value = DBNull.Value
Else
value = prop.GetValue(obj, Nothing)
End If
End If
param = ConnSql.CreateParameter("@" & prop.Name, value)
params.Add(param)
End If
Catch ex As Exception
End Try
Next
sql = sql.Substring(0, sql.Length - 1)
Return sql
End Function
如果,则不需要以下
。您可以删除它
如果prop.PropertyType.IsGenericType和prop.PropertyType.GetGenericTypeDefinition()=GetType(可为null(Of)),则
但是如果
,您确实需要修复以下问题:
If prop.GetValue(obj, Nothing) = Nothing Then
到
--
完整代码:
您需要检查HasValue吗?您能调用GetValue并查看是否没有返回任何内容吗?
If prop.GetValue(obj, Nothing) IS Nothing Then
Private Function GetUpdateQuery(ByVal obj As Object, ByRef params As List(Of SqlParameter), Optional ByVal excl As String() = Nothing) As String
Dim sql As String = String.Empty
Dim props As PropertyInfo() = obj.GetType().GetProperties
If excl Is Nothing Then
excl = New String() {}
End If
For Each prop As PropertyInfo In props
If Not excl.Contains(prop.Name) And prop.CanWrite = True Then
sql &= String.Format("{0} = @{1},", prop.Name, prop.Name)
Dim param As SqlParameter
Dim value As Object
If prop.GetValue(obj, Nothing) Is Nothing Then
value = DBNull.Value
Else
value = prop.GetValue(obj, Nothing)
End If
param = ConnSql.CreateParameter("@" & prop.Name, value)
params.Add(param)
End If
Next
sql = sql.Substring(0, sql.Length - 1)
Return sql
End Function