Good day all
I wrote the following method:
private void RegisterEvent(object targetObject, string eventName, string methodName)
{
EventInfo eventInfo = targetObject.GetType().GetEvent(eventName);
MethodInfo method = eventInfo.EventHandlerType.GetMethod("Invoke");
IEnumerable<Type> types = method.GetParameters().Select(param => param.ParameterType);
DynamicMethod dynamicMethod = new DynamicMethod(eventInfo.EventHandlerType.Name, typeof (void), types.ToArray(), typeof (QueryWindow));
MethodInfo methodInfo = typeof (QueryWindow).GetMethod(methodName, new[] { typeof (object) });
ILGenerator ilGenerator = dynamicMethod.GetILGenerator(256);
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.EmitCall(OpCodes.Call, methodInfo, null);
dynamicMethod.DefineParameter(1, ParameterAttributes.In, "sender");
dynamicMethod.DefineParameter(2, ParameterAttributes.In, "e");
// Get an argument exception here
Delegate methodDelegate = dynamicMethod.CreateDelegate(eventInfo.EventHandlerType, this);
eventInfo.AddEventHandler(targetObject, methodDelegate);
}
I get ArgumentException with the message
Error binding to target method.
in the line
Delegate methodDelegate = dynamicMethod.CreateDelegate(eventInfo.EventHandlerType, this);
Could anyone point out on my mistake?
Thanks in advance.