Reflection - Iterate object's properties recursively within my own assemblies (Vb.Net/3.5)

后端 未结 2 534
北荒
北荒 2021-01-28 01:27

I wonder if anyone can help me - I\'ve not done much with reflection but understand the basic principles.

What I\'m trying to do:

I\'m in the pr

2条回答
  •  日久生厌
    2021-01-28 02:18

    This will hopefully get you started. It prints a tree directly to the console so you'll need to adjust to output XML. Then change the IsMyOwnType method to filter out the assemblies you're interested in, right now it only cares about types in the same assembly as itself.

    Shared Sub RecurseProperties(o As Object, level As Integer)
        For Each pi As PropertyInfo In o.GetType().GetProperties()
            If pi.GetIndexParameters().Length > 0 Then Continue For
    
            Console.Write(New String(" "c, 2 * level))
            Console.Write(pi.Name)
            Console.Write(" = ")
    
            Dim propValue As Object = pi.GetValue(o, Nothing)
            If propValue Is Nothing Then
                Console.WriteLine("")
            Else
                If IsMyOwnType(pi.PropertyType) Then
                    Console.WriteLine("")
                    RecurseProperties(propValue, level+1)
                Else
                    Console.WriteLine(propValue.ToString())
                End If
            End If
    
        Next
    End Sub
    
    Shared Function IsMyOwnType(t As Type) As Boolean
        Return t.Assembly Is Assembly.GetExecutingAssembly()
    End Function
    
        

    提交回复
    热议问题