object reflection

R

RP

Hi all,

I have a class object that has member classes and structures. I basically
want to be able to write some code that writes out all the names of the
member variables in the class object and their values. e.g.

Public Structure Person
Public fname, mname, lname as string
End Structure

Public Structrue Department
Public departmentcode as integer
Public departmentname as string
End Structure

Public Class Employee
Public P as Person
Public D as Department
End Class

With my code I would like some output like:

Employee.P.fname = Param
Employee.P.mname =
Employee.P.lname = Dawson
Employee.D.departmentcode = 1
Employee.D.departmentname = Technology

Any assistance would be greatly appreciated.

TIA
 
K

Ken Tucker [MVP]

Hi,

Add a public overrides function tostring to your structure.

Public Class Employee

Public P As Person

Public D As Department

Public Overrides Function Tostring() As String

Dim strout As String

strout = String.Format("Person {0} {1} {2}", P.fname, P.mname, P.lname)

strout &= ControlChars.NewLine & String.Format("Department {0} {1}",
D.departmentcode, D.departmentname)

Return strout

End Function

End Class



Ken
 
R

RP

Ken, that would work but I was kind of looking for some code that given an
instance of a variable E the code uses reflection to extract the members and
echo the names and values they hold.

thanks a bunch
 
D

dev

I think this misght be wwhat you are looking for. I am setting the values
of the properties, but I believe there is a GetValue. Im using a
PropertyInfo but the is MethodInfo and some others. Check it out.



Try

Dim arrproperties() As PropertyInfo

'get the type corresponding to the class

Dim t As System.Type = Type.GetType(Me.ToString)

'we're not interested in primitives or value types

If (t.IsClass) Then

arrproperties = t.GetProperties()

End If

Dim p As PropertyInfo

For i = 0 To UBound(arrProps)

For j = 0 To UBound(arrproperties)

p = arrproperties(j)

If LCase(p.Name) = LCase(arrProps(i)) Then

p.SetValue(Me, arrProps(i + 1), Nothing)

End If

Next

i += 1

Next

Return True

Catch ex As Exception

m_cTWriter.WriteTraceError(ex)

Return False

End Try
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top