【问题标题】:Find a property inside a class that match List<class>在类中查找与 List<class> 匹配的属性
【发布时间】:2016-05-27 18:16:03
【问题描述】:

对于item列表的显示,我需要用通用的方式来判断item是否有这个item的列表,这是一个简单的递归循环。

我已经尝试过像这样使用反射

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 )

我的问题是 prop 永远是 PropertyInfo 而不是我可以比较的真实类型。

感谢您的帮助。

编辑:

通过了一些测试,我发现了这一点,最后一件事是如何将 prop.Name = "lst" 替换为 prop.Type = typeof(item)

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 

【问题讨论】:

  • 为什么不能使用If item.lst IsNot Nothing Then... 而不是反射?
  • 因为我不知道该物业的名称。我只知道那个类有一个属性是 List 来进行递归循环。
  • 代码在寻找PersonneSampleModel类型,怎么会不知道那个类型的props呢?
  • 它代表一个实现。它将是 PersonneSampleModel 或 FooSampleModel 或任何具有属性 List 的类。我确实检索了这个属性。
  • 如果我弄错了,请纠正我,但就您的代码而言,它正在检查列表中的每个项目以查看该项目是否是 PersonneSampleModel 的列表,但是您创建的列表中的项目是不是 PersonneSampleModel 列表,它们只是 PersonneSampleModel 对象。

标签: vb.net reflection types


【解决方案1】:

您必须在运行时使用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 

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 2022-07-22
    • 1970-01-01
    • 2014-05-26
    • 2014-09-17
    • 2019-07-15
    • 2016-07-02
    • 2022-06-29
    • 1970-01-01
    相关资源
    最近更新 更多