Reputation: 63
how to add a event handler myhandler
using reflection if I only have the type AType
of the event thrower?
Delegate myhandler = SomeHandler;
EventInfo info= AType.GetEvent("CollectionChanged");
info.AddEventHandler( ObjectOfAType, myhandler )
Upvotes: 1
Views: 1656
Reputation: 1062770
Basically, what you have is fine. The only glitch is that myhandler
actually needs to be of the correct type, which is to say: of the type defined by the event.
For example:
using System;
using System.Collections.Specialized;
using System.Reflection;
class Program
{
static void Main()
{
Type AType = typeof(Foo);
var ObjectOfAType = new Foo();
Delegate myhandler = (NotifyCollectionChangedEventHandler)SomeHandler;
EventInfo info = AType.GetEvent("CollectionChanged");
info.AddEventHandler(ObjectOfAType, myhandler);
// prove it works
ObjectOfAType.OnCollectionChanged();
}
private static void SomeHandler(object sender, NotifyCollectionChangedEventArgs e)
=> Console.WriteLine("Handler invoked");
}
public class Foo
{
public void OnCollectionChanged() => CollectionChanged?.Invoke(this, null);
public event NotifyCollectionChangedEventHandler CollectionChanged;
}
There is a Delegate.CreateDelegate()
method that takes a delegate type, an object instance, and a MethodInfo
method; you can use this (using the event-type from EventInfo info
) to create an appropriate delegate instance for a given method on a particular object.
Upvotes: 1