Reflection Question

D

Doug Handler

I'm trying to invoke a method that returns a value (actually a Panel), but i
keep getting an error:

System.Reflection.TargetException was unhandled
Message="Object does not match target type."

Here's the code:

MethodInfo methodInfo = typeChannelPanel.GetMethod("CreateNavPanel");

Panel o_Panel = (Panel)methodInfo.Invoke(methodInfo, null);

I've tried creating it as an Object and i get the same error. The
CreateNavPanel returns a Panel, which i then need to add to the main form.
What am i missing here?
 
M

Marc Gravell

The first parameter of methodInfo.Invoke is the target object i.e. if you
were doing it in "normal" code

myPanel.CreateNavPanel();

then the equivalent in reflection would be

methodInfo.Invoke(myPanel, null);

Does that make sense? The only exception is for static methods, where you
can pass null into the first argument.

Your code attempts to execute the method on the methodInfo object, hence the
error.

Marc
 
D

Doug Handler

Marc,

Thanks...figured it out.

Cheers.
Marc Gravell said:
The first parameter of methodInfo.Invoke is the target object i.e. if you
were doing it in "normal" code

myPanel.CreateNavPanel();

then the equivalent in reflection would be

methodInfo.Invoke(myPanel, null);

Does that make sense? The only exception is for static methods, where you
can pass null into the first argument.

Your code attempts to execute the method on the methodInfo object, hence
the error.

Marc
 

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