Click to See Complete Forum and Search --> : Set Property via Reflection


victor
10-21-2002, 12:28 PM
Hello!

I have a simple class and want to pass its name, create instance and set
property at run time. I use reflection and sample code from MSDN, but it
does not run. Any ideas?

Thanks

Victor

Public Class CTestReflect
Dim m_value As String

Public Property Value()
Get
Value = m_value
End Get
Set(ByVal Value)
m_value = Value
End Set
End Property

Public Sub ShowValue()
MsgBox(m_value)
End Sub
End Class

'!!!
'I want to set its Value property at run-time using Reflection

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
m_*** = [Assembly].LoadFrom("c:\TestReflect\bin\TestReflect.dll")
Dim obj As Object = m_***.CreateInstance("TestReflect.CTestReflect")
Dim tp As Type = obj.GetType()
Dim arr As Array = tp.GetProperties()
Dim arg(1) As Object
arg(0) = "Set Value"

Try
Dim memInfoArr As Array = tp.GetMember("Value")
Dim memInfo As MemberInfo = CType(memInfoArr(0), System.Reflection.MemberInfo)

'!!!
'I QUERY THE TYPE AND IT RETURNS THE NAME
MsgBox(memInfo.MemberType.ToString())
MsgBox(memInfo.Name)
MsgBox(memInfo.GetType().ToString())
'!!!
'HERE WHERE IT BOMBS
'IT SAYS THAT METHOD WITH THAT NAME NOT FOUND EVEN I USE NAME JUST RETUREND
tp.InvokeMember(memInfo.Name, BindingFlags.Public Or BindingFlags.SetProperty,
Nothing, obj, arg)

Catch err As Exception
MsgBox(err.Message)
End Try
End Sub

Mattias Sjögren
10-21-2002, 06:23 PM
Victor,

You might have to include BindingFlags.Instance among the other
BindingFlags. Also note that

Dim arg(1) As Object

declares an array of length 2.

But you're really making things more complicated than necessary. An
easier way would be

Dim pi As PropertyInfo = tp.GetProperty("Value")
pi.SetValue(obj, "Set Value", Nothing)



Mattias

===
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.