Reflection Question

  • Thread starter Thread starter Doug Handler
  • Start date Start date
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?
 
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
 
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
 
Back
Top