Search code examples
vb.netpropertyinfogetpropertiesbindingflags

How to I get the parent property's class type after using GetProperties to get a list of properties on a class?


I'm using GetProperties to get a list of properties for a class.

Dim properties As List(Of PropertyInfo) = objType.GetProperties(BindingFlags.Instance Or BindingFlags.Public).ToList()
For Each prop As PropertyInfo In properties
    'how do I get the parent class type of the prop (level up in hierarchy from property's ReflectedType)?
Next

How do I get the parent class's one level up of the current property's ReflectedType? Note that this class could have multiple parent levels. I don't want the BaseType of the current property's class, but simply the next level up in the hierarchy of the property's ReflectedType as a property could be several layers deep.


Solution

  • I'd try an approach like this - basically a loop walking up the inheritance tree...

    Public Function WalkInheritanceFromProperty(pi As PropertyInfo) As List(Of Type)
       Dim currentType As Type = pi.ReflectedType
       Dim parentType As Type
       Dim lst As New List(Of Type)
    
       Do
          parentType = currentType.BaseType
          If Not parentType Is Nothing Then lst.Add(parentType) Else Exit Do
          currentType = parentType
       Loop While Not parentType Is Nothing
       Return lst
    End Function
    

    Here is some info that may help: https://msdn.microsoft.com/en-us/library/system.type.basetype(v=vs.110).aspx