Reputation: 717
I've an Issue with System.Reflection, when I call MethodInfo.Invoke method it gaves me the TargetException exception that says: Object does not match with target, Here the code:
object[] parms = new object[] { path };
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Type gameType = null;
foreach (Assembly asm in assemblies)
{
string asmName = asm.GetName().Name;
if (asmName == "Tester")
{
gameType = asm.GetType("Tester.Main");
break;
}
}
var game = Convert.ChangeType(GameInstance, gameType);
Type delegateType = game.GetType().GetEvent("gameVideoLoader").EventHandlerType;
MethodInfo method = delegateType.GetMethod("Invoke");
method.Invoke(game, parms); // Here the exception
Any Idea? PS: game object is correctly assigned so it's not null
Upvotes: 0
Views: 1186
Reputation: 22739
What Jon said.
Also, if you're trying to do some hacking (and not production-level code), here's some practical advice: take a look at the source code (or use a disassembler such as Reflector or dotPeek) and see how the event is invoked.
Otherwise, if the event is using a compiler-generated field, use Type.GetField
to retrieve the field (it would have the same name as the event) and then call GetValue
to get the actual delegate
If the delegate type is public, cast the value and invoke
((MyDelegate)fieldValue)(arg1, arg2...)
Otherwise, cast to Delegate
and use the dynamic invoke method
((Delegate)fieldValue).DynamicInvoke(new object[] { arg1, arg2 })
Upvotes: 2
Reputation: 1500375
You're trying to call the delegate's Invoke
method, but on a Tester.Main
instance. That's just wrong - because the Tester.Main
instance isn't an instance of the appropriate delegate.
If you're trying to actually raise the gameVideoLoader
event, then that's a different matter... and something that you shouldn't be doing anyway. The purpose of events is to allow clients to subscribe and unsubscribe handlers - the object itself should be responsible for raising the event. You may be able to find an underlying field which is used to implement the event, get the value of that field and invoke the delegate - but I'd strongly advise against it. You're basically going against the design of events at this point.
Upvotes: 1