You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取类及子类属性名时遇IList类型‘对象不匹配目标类型’错误

问题解决:深度遍历类及泛型List属性时的类型匹配错误

错误原因

你的代码在递归处理子类型属性时,错误地传递了父对象作为参数。例如处理Address.Floors时,递归调用GetProperties传入的是Address实例,但后续遍历Floor的Peoples属性时,代码会尝试从Address实例获取Peoples属性——而Address根本没有这个属性,因此抛出“对象不匹配目标类型”错误。

修正后的代码

修正后的GetProperties方法

Private Sub GetProperties(Obj As Object, ObjType As Type, Indent As Integer)
    Dim Pre = Strings.StrDup(Indent, " ")
    For Each P As PropertyInfo In ObjType.GetProperties
        If P.PropertyType.IsEnum Then
            Result &= Pre & P.Name & " (Enum: " & P.PropertyType.Name & ") ->"
            Dim EnumValues = System.Enum.GetValues(P.PropertyType)
            For Each V In EnumValues
                Result &= Pre & " [" & V & "=" & V.ToString & "]"
            Next
            Result &= vbCrLf
        ElseIf GetType(IList).IsAssignableFrom(P.PropertyType) AndAlso P.PropertyType.IsGenericType Then
            Result &= Pre & "[" & P.Name & "] Generic " & P.PropertyType.Name & vbCrLf

            ' 获取泛型List的元素类型
            Dim elementType = P.PropertyType.GetGenericArguments()(0)
            ' 仅处理自定义类(排除系统类)
            If elementType.IsClass AndAlso Not elementType.FullName.StartsWith("System") Then
                ' 创建元素类型的实例(空List时也能正常处理)
                Dim elementInstance = Activator.CreateInstance(elementType)
                Indent += 4
                GetProperties(elementInstance, elementType, Indent)
                Indent -= 4
            End If
        Else
            If P.PropertyType.IsClass AndAlso Not P.PropertyType.FullName.StartsWith("System") Then
                ' 获取当前属性的实例,为空则创建新实例
                Dim propInstance = P.GetValue(Obj)
                If propInstance Is Nothing Then
                    propInstance = Activator.CreateInstance(P.PropertyType)
                End If
                Indent += 4
                GetProperties(propInstance, P.PropertyType, Indent)
                Indent -= 4
            Else
                Result &= Pre & P.Name & " " & P.PropertyType.Name & vbCrLf
            End If
        End If
    Next
End Sub

核心修正点

  1. 自定义类属性处理:获取当前属性对应的实例(若为空则通过Activator.CreateInstance创建),将该实例传入递归方法,确保后续遍历的是当前属性类型的属性。
  2. 泛型List处理:直接从List的泛型参数中提取元素类型,创建元素实例后传入递归,不再依赖父对象,避免类型不匹配问题。

内容的提问来源于stack exchange,提问作者Hans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 23:01:02