Friday, March 16, 2012

Looping Through Object Properties -- How do I?

I have a class as follows:


Public Class Myclass
Public Property MyProperty1
Public Property MyProperty2
End class

I need to have a method which will loop through these properties in run time (may be using reflection?)

Something like...


Dim objmyClass as New Myclass
For i = 0 to obj.Properties.count
... Do something with the property...
Next

Is this possible?Yes, that would be using reflection.

Dim objmyClass As New Myclass

Dim objmyClassType As Type = objmyClass.GetType()
Dim objmyClassProperties As System.Reflection.PropertyInfo() = objmyClassType.GetProperties( (BindingFlags.Public Or BindingFlags.Instance) )

'The binding flags is what determines which properties to get ( ex. public, private, shared, instance, etc... )

For Each currentProperty As PropertyInfo In objmyClassProperties

... Do somethign with the property

Next


Using reflection its possible
Reflection is exactly what you need to use. Seethis page in the .NET Class Library.

0 comments:

Post a Comment