Mekroebo
Mekroebo

Reputation: 461

CreateDelegate: 'Cannot bind to the target method because its signature is not compatible with that of the delegate type.'

I'm running into a weird issue that I just don't understand.

What I'm trying to do is pretty straight forward: Dynamically load an assembly, locate an event with a pre-defined name and hook to that event.

The code to do so is simple:

private void AttachToEvent(Type type)
{
    if (type == null) return;

    foreach (var @event in type.GetEvents())
    {
        if (@event.Name != EVENTNAME) continue;

        var eventHandler = typeof(Handler).GetMethod(DELEGATEMETHOD, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

        if (@event == null || eventHandler == null) return;

        var @delegate = Delegate.CreateDelegate(@event?.EventHandlerType, eventHandler);

        @event.AddEventHandler(type, @delegate);
    }
}

The DELEGATEMETHOD is defined as follows:

public void LogHandler(DateTime dateTime, string connectorName, string severity, string details)
{
  // do something with the received log event...
}

In the loaded assembly, the event is defined as this:

public delegate void LogHandler(DateTime dateTime, string connectorName, string severity, string details);
public event LogHandler OnLogEventReceived;

Whatever I try to do, I always get the 'Cannot bind to the target method because its signature is not compatible with that of the delegate type.' error which (by my knowledge) would mean that the arguments defined in the delegate are not the same as the arguments in the target method. But in my case... they do match!

Does anybody have an idea what is going on here?

Upvotes: 3

Views: 8437

Answers (3)

Ed Harling
Ed Harling

Reputation: 74

I was getting this error when my events had an incorrect parameter type, that is, the EventArgs type did not match the event definition.

Upvotes: 0

Hossein Khoddami
Hossein Khoddami

Reputation: 1

In the form, you must send ((this) current class instance) as parameters like:

Delegate del = Delegate.CreateDelegate(handlerType, this, method);
@event.AddEventHandler(button, del);

Upvotes: 0

shingo
shingo

Reputation: 27086

If you read the documentation, you'll find the method you chosen is for static method. You should use a method for instance method, e.g. CreateDelegate(Type, Object, MethodInfo). In this case you need provide an instance of Handler class.

Delegate.CreateDelegate(@event?.EventHandlerType, new Handler(), eventHandler);

Upvotes: 5

Related Questions