在类中找到与List <class>

时间:2016-02-16 12:46:38

标签: vb.net reflection types

为了显示项目列表,我需要通过通用的方式来确定项目是否有这个项目的列表,这是一个简单的递归循环。

我已尝试使用Reflection作为此

Dim detail As New List(Of PersonneSampleModel) From {New PersonneSampleModel With {.Id = 50, .Nom = "Details_Robert", .Prenom = "Details_titi"}}

Dim p = New PersonneSampleModel With {.Id = 1, .Nom = "Robert", .Prenom = "titi", .lst = detail}
Dim p2 = New PersonneSampleModel With {.Id = 2, .Nom = "Jean", .Prenom = "titi2"}
Dim p3 = New PersonneSampleModel With {.Id = 3, .Nom = "Dupont", .Prenom = "titi3"}
Dim p4 = New PersonneSampleModel With {.Id = 4, .Nom = "Sean", .Prenom = "titi3"}
Dim p5 = New PersonneSampleModel With {.Id = 5, .Nom = "Paul", .Prenom = "titi3"}
Dim p6 = New PersonneSampleModel With {.Id = 6, .Nom = "Durant", .Prenom = "titi3"}
Dim lst As New List(Of PersonneSampleModel) From {p, p2, p3, p4, p5, p6}

For Each item In lst
    For Each prop in item.GetType().GetProperties           
        If TypeOf prop Is List(of PersonneSampleModel) ' <= how to determine if prop is List<item> 
            prop.Dump()
        End if          
    Next
Next 

不工作:

If TypeOf prop Is List(of item.GetType()) 'item.GetType() not defined

If TypeOf prop Is List(of PersonneSampleModel) ' PropertyInfo is not List(of )

我的问题是道具是PropertyInfo,而不是我可以比较的真实类型。

感谢您的帮助。

编辑:

一些测试通过了,我发现了这个,最后一件事是如何用prop.Type = typeof(item)替换prop.Name =“lst”

For Each item In lst
    item.Dump("item")
    item.lst.Dump("item.lst")
    For Each prop in item.GetType().GetProperties           
        if prop.Name = "lst"
            dim l As new List(Of PersonneSampleModel) 
            l = item.GetType().GetProperty("lst").GetValue(item, nothing)       
            l.Dump("Value")
            prop.Dump("prop")
        end if 
    Next
Next 

1 个答案:

答案 0 :(得分:0)

您必须使用MakeGenericType()方法在运行时创建类型化列表类型,然后将其与属性类型进行比较。

For Each item In lst
    For Each prop in item.GetType().GetProperties       
        If GetType(List(of )).MakeGenericType(item.GetType()) = prop.PropertyType Then
            Dim innerList = prop.GetValue(item)
            If innerList IsNot Nothing Then
                Console.WriteLine("list found")
            End if
        End if          
    Next
Next