Greg Gum
Greg Gum

Reputation: 37909

How to wire up event with reflection

See below sample. I need to wire up the DoSomething method obtained though reflection to an event.

    class Program {
    private static event EventHandler MyEvent;

    static void Main(string[] args)
    {
        object aType = new SomeType();

        var type = aType.GetType();

        var method = type.GetMethod("DoSomething");

        if (method != null)
        {
            MyEvent += method;//How do I wire this up?
        }
    }
}


public class SomeType {
    public void DoSomething() {
        Debug.WriteLine("DoSomething ran.");
    }
}

Upvotes: 0

Views: 135

Answers (2)

SLaks
SLaks

Reputation: 887469

You need to create a delegate:

MyEvent += (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), aType, method);

The second argument is the instance to bind the delegate to.
For more information, see my blog.

Like any other delegate, this will only work if the target method has the same signature (parameter types) as the delegate.

Upvotes: 4

Thomas Levesque
Thomas Levesque

Reputation: 292465

Actually, you can't use DoSomething as a handler for MyEvent, because it doesn't have the right signature. Assuming you change the signature of DoSomething to this:

public void DoSomething(object sender, EventArgs e)

You can subscribe to the event like this:

    if (method != null)
    {
        var dlg = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), aType, method);
        MyEvent += dlg;
    }

Upvotes: 4

Related Questions