【问题标题】:How to I get the parent property's class type after using GetProperties to get a list of properties on a class?使用 GetProperties 获取类的属性列表后如何获取父属性的类类型?
【发布时间】:2017-04-11 19:43:30
【问题描述】:

我正在使用 GetProperties 来获取一个类的属性列表。

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

如何让父类比当前属性的ReflectedType 高一级?请注意,此类可能有多个父级别。我不想要当前属性类的BaseType,而只是属性的ReflectedType 层次结构中的下一层,因为属性可能有好几层深。

【问题讨论】:

    标签: vb.net propertyinfo getproperties bindingflags


    【解决方案1】:

    我会尝试这样的方法 - 基本上是一个循环遍历继承树...

    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
    

    这里有一些信息可能会有所帮助:https://msdn.microsoft.com/en-us/library/system.type.basetype(v=vs.110).aspx

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 2019-09-28
      • 2010-10-18
      • 1970-01-01
      • 2021-07-16
      • 2018-03-19
      • 2023-03-13
      • 2018-08-12
      相关资源
      最近更新 更多