mercredi 5 août 2015

Creating a proxy delegate using reflection for any event

I am trying to write a library that allows the attaching of events using attributes, and I want to create a set of convenience method signatures.

For example, a button will have a Click event with a handler signature of void(object, EventArgs).

I have already mapped the methods that match this signature directly:

// the object that raises the event
Object eventSource = ...;
EventInfo evnt = ...; 

// the object with the target method
Object target = ...;
MethodInfo method = ...;

// create and attach delegate
var del Delegate.CreateDelegate(evnt.EventHandlerType, target, method);
evnt.AddEventHandler(eventSource, del);

This works well as long as the methods are the same/compatible, even when detaching an event:

evnt.RemoveEventHandler(eventSource, del);

However, I would like to also be able to map parameterless methods. Is it possible to create a delegate that will accept any arguments, but then ignore them, and invoke a desired method on an object?

For an example, in the working bit, I can do:

// the method
void MyClickMethod(object sender, EventArgs e)
{
}

// the execution
var evnt = myButton.GetType().GetEvent("Click");
var method = this.GetType().GetMethod("MyClickMethod")
AttachEvent(/*eventSource*/ myButton, /*evnt*/ evnt, /*target*/ this, /*method*/ method);

But, I would also like to be able to attach this method:

void MyClickMethod()
{
}

My logic here is that we can attach any parameterless method on any type to any event. This is often very helpful. It is important that I be able to detach any events.

What goes on in my mind, would to somehow create a delegate that does this:

eventSource.Event += (sender, e) => {
    target.method();
};

Is there a way to do this cleanly?





Aucun commentaire:

Enregistrer un commentaire