gpt4 book ai didi

vb.net - 如何通过反射对对象的可为空属性调用 HasValue?

转载 作者:行者123 更新时间:2023-12-02 01:59:52 24 4
gpt4 key购买 nike

此函数循环对象的所有属性以创建更新查询以将对象保存到数据库。

由于引入了可为 null 的属性,我们必须对其进行一些更改。如果该属性可为空,我们想检查“HasValue”属性。当它具有值(value)时,这确实有效。当该属性没有值时,我们会在 CBool​​ 行收到“非静态方法需要目标”错误

有什么建议吗?使用反射检查属性的“HasValue”属性的另一种方法?

谢谢。


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

最佳答案

您不需要以下If。您可以将其删除。

If prop.PropertyType.IsGenericType AndAlso prop.PropertyType.GetGenericTypeDefinition() = GetType(Nullable(Of )) Then

但是您确实需要修复以下If:

If prop.GetValue(obj, Nothing) = Nothing Then

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

关于vb.net - 如何通过反射对对象的可为空属性调用 HasValue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3718279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com