使用反射迭代类属性

时间:2014-09-01 14:34:16

标签: vb.net reflection

我正在尝试使用反射迭代我的类属性,我尝试使用这里的几个线程作为指导但是propertyInfo数组总是不返回任何内容。

Public Sub GetProperties(ByRef objType As Type)

    Dim propertyInfo() As PropertyInfo = objType.GetProperties((BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.DeclaredOnly))

    For Each propertyItem As System.Reflection.PropertyInfo In propertyInfo
        Console.WriteLine(propertyItem.Name & " is of type " & propertyItem.PropertyType.ToString)
        Console.WriteLine(vbCrLf & vbCrLf)
    Next

End Sub

Imports System.Data.SqlClient
Imports System.Web
Imports System.IO
Public Class Collection
    Inherits AppBase
    Public Sub New(ByVal newConnectionString As String, ByVal newAppBrand As String, ByVal newRepID As Integer)
    MyBase.New(newConnectionString, newAppBrand, newRepID)
End Sub

Public Class CollectionRecord
    Inherits AppRecord

    Public collectionID As Integer
    Public name As String
    Public sqmBasePrice As Long
    Public summary As String
    Public imageName As String
End Class

Module DownloadData
   Public Function CheckData
      Dim collectionRecord as new CollectionRecord
      GetProperties(collectionRecord)
   End Function
End Module

如果我用GetProperties参数中的字符串类型替换我的自定义类,我会得到两个返回的属性。 有什么想法吗?

由于 保罗

1 个答案:

答案 0 :(得分:1)

您已定义了一个类型CollectionRecord,其中包含五个字段,但没有属性。

Public Class CollectionRecord
    Inherits AppRecord

    Public collectionID As Integer
    Public name As String
    Public sqmBasePrice As Long
    Public summary As String
    Public imageName As String
End Class

然后使用反射API迭代该类型的属性

这里的解决方案是:

  1. 遍历您的类型字段而不是属性
  2. 重新定义您的类型以获取属性而不是字段MSDN
  3. 1& 2会起作用,这取决于你的需求。