Simple Reflection Question

  • Thread starter Thread starter Damien Sawyer
  • Start date Start date
D

Damien Sawyer

Hi all,

Let's say that I have an object oPerson as type clsPerson.

clsPerson has a string property called, say, sName.

Now - I have a database table which has 'as strings' the names of the
properties of clsPerson for which I need to get values.

So - given my string "sName" and instantiated object oPerson, how do I
return the value of "sName" from oPerson.

Can someone please point me in the right direction?

Thanks very much in advance,



Damien Sawyer
 
Found it! I'll post the solution if anyone's interested.


DS
<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

Imports System

Imports System.Reflection



Module Module1

Sub Main()

' Create an instance

Dim oOb As clsPerson = New clsPerson(1, "Jesus")

' Get Type of order

Dim oType As Type = GetType(clsPerson)

' Note - this also works.

'Dim otype = oOb.GetType

' Get Value

Dim pPropInfo As PropertyInfo = oType.GetProperty("sName")

Dim sValue As String = pPropInfo.GetValue(oOb, Nothing)

'Display

MsgBox(sValue)

End Sub

End Module

Public Class clsPerson

Private p_id As Int16

Private p_Name As String

Sub New(ByVal iID As Int16, ByVal sName As String)

Me.p_id = iID

Me.p_Name = sName

End Sub

ReadOnly Property sName() As String

Get

Return Me.p_Name

End Get

End Property

ReadOnly Property iID() As Int16

Get

Return Me.p_id

End Get

End Property

End Class
 
Damien,

You know that using Int16 gives you a slightly lower performance on 32bits
computers with a 32bit OS.

Cor
 
And if the data comes from SQL Server then it would also be recommended to
use a 32-bit int

By the way is there any specific reason (current project, ...) why you want
to use reflection to retrieve the value of the property?

Gabriel Lozano-Morán
 
Back
Top