Paulo Augusto Künzel wrote:
Thanks, but I've been on stuck on the right track for over a couple days. I can't find neither material nor people that can help me. It is getting a bit frustrating.
I repeat, that is quite easy. Look, if you want to practice, some ready-to-use code sample will not allow you to practice on your own experience, will be nearly useless. That's why I don't want to write the code for you. To really help, I want to give you some hints, because I know where some people typically got stuck.
I never used anything but regular MSDN documentation; so you, too, don't need anything else, just act by definition.
You have two types, property type and list box type; you need to reflect both. You reflect the type of the list box, get instance of the Items property. This is done by invocation of the property getter. (Was that so hard to guess? This point could be a reason why you stuck. Call the getter.) You already have the instance of the list box, so use it to pass to the getter, which is an
instance (non-static) method.
When you got an instance of the
Items
property, it's time to forget the instance of the list box. Reflect the type of
Items
and find the method you want. This is of course also the
instance method, so to call it, you need to pass the instance of the
Items
you obtained on the next step.
So, in addition to what you already found, you need to learn how to get an accessor ("getter"):
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getmethod.aspx[
^].
[EDIT]
Something like:
PropertyInfo pi =
MethodInfo mi = pi.GetMethod;
object itemsInstance = mi.Invoke();
[END EDIT]
And you also need to know how to invoke an instance method:
http://msdn.microsoft.com/en-us/library/a89hcwhh%28v=vs.110%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/4k9x6bc0%28v=vs.110%29.aspx[
^].
In invocation of the method, pay attention for the parameter
Object obj
. This is how you pass the instance of the object on which you invoke the method ("this" reference in the method implementation).
All this is really, really easy. You will see.
Now, in practice, you should understand that using reflection to find anything by some string representing the name is a bad practice (it is needed in, say, implementation of the IDE
designers though), because such solutions are not supportable. Imagine what can happen if you rename some method or simply misspell the string with a method name. The compiler won't detect a problem, but such solution will stop working. One robust approach is finding an interface implemented by some class/structure, found by interface definition, not by its name. Than you can call interface method of this type instance quite safely.
—SA