Vb.net 通过具有列表(of)的对象递归反射
希望使用反射来获取对象名称和值。我能够通过DocumentConfig类,但无法获取字段。也不希望将gettype标识为列表。如果强制进入列表(of)返回消息fielditems不是DocumentConfig类的成员Vb.net 通过具有列表(of)的对象递归反射,vb.net,class,reflection,Vb.net,Class,Reflection,希望使用反射来获取对象名称和值。我能够通过DocumentConfig类,但无法获取字段。也不希望将gettype标识为列表。如果强制进入列表(of)返回消息fielditems不是DocumentConfig类的成员 Public Class MyDocuments Public Class DocumentConfig Private _Name As String Public Property Name() As String Public Property Fi
Public Class MyDocuments
Public Class DocumentConfig
Private _Name As String
Public Property Name() As String
Public Property Fields() As New List(Of FieldItems)
End Class
Public Class FieldItems
Private _Name As String
Public Property Name() As String
End Class
End Class
Module Module1
Sub Main()
Dim Document As New List(Of FieldItems)
Document.Add(New FieldItems With {.Name = "Invoice"})
Document.Add(New FieldItems With {.Name = "Statement"})
Document.Add(New FieldItems With {.Name = "Reminder"})
End Sub
Public Sub DisplayAll(ByVal Someobject As DocumentConfig)
Dim _type As Type = Someobject.GetType()
Console.WriteLine(_type.ToString())
Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance
Dim properties() As PropertyInfo = _type.GetProperties(flags)
For Each _property As PropertyInfo In properties
Dim valuetype = _property.GetType()
If [_property].PropertyType = GetType(String) OrElse [_property].PropertyType = GetType(Integer) OrElse [_property].PropertyType = GetType(Boolean) then
Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing))
ElseIf _property.PropertyType = GetType(List(Of)) Then
Dim list = [_property].GetValue(Someobject, Nothing)
For Each item In list
DisplayAll(item)
Next
Else
Console.WriteLine("Name: " + _property.Name)
End If
Next
End Sub
End Module
这是因为List(Of)
和List(Of FieldItems)
实际上是两种不同的类型,就像List(Of FieldItems)
和List(Of String)
是两种不同的类型一样
调用GetType(List(Of))
时,它返回一个Type
,表示基本的泛型类(通常写为List
,“T”是将要使用的类型的占位符)。但是您要查找的属性字段
的类型是列表
,而不是列表
如果您将代码更改为
ElseIf _property.PropertyType = GetType(List(Of FieldItems)) Then
那就是我们应该工作
另一方面,如果您需要代码能够用于任何类型的列表
,则可以使用type.IsGenericType
来判断类型
是否为泛型类型,然后使用type.GetGenericTypeDefinition
来确定它是哪种泛型类型。例如,以下代码将在if语句中返回True
:
(New List(Of String)).GetType.GetGenericTypeDefinition = GetType(List(Of))
另一个注意事项是,用括号声明属性并不像以前那样常见
Public Property Fields() As New List(Of FieldItems)
应该是
Public Property Fields As New List(Of FieldItems)
在VB.NET中那样的变量上加括号通常意味着您正在声明一个数组,例如:
Dim foo()As String
创建一个字符串数组。实际上,它并不是以您使用它们的方式声明数组,但它们具有误导性且不必要。根据(字段项的)列表进行调整是可行的。。谢谢但是,一旦尝试显示所有(项目)接收错误“无法将对象类型“fielditems”设置为DocumentConfig。建议?通过将某个对象更改为DocumentConfig以仅对象,更正了我收到的错误。非常感谢!伟大的那就请吧。