1

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 )
EpicKip
  • 4,015
  • 1
  • 20
  • 37
Fabian
  • 63
  • 11
  • 1
    you've already obtained the `EventInfo`, so that's good; now - what happens? is the problem that `myhandler` is not actually of the right type? or...? – Marc Gravell Mar 27 '18 at 12:05

1 Answers1

1

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Also if you want to create an `ObjectOfAType` dynamically you could do something like this: `var ObjectOfAType = Activator.CreateInstance(null, "Namespace.Foo").Unwrap(); var AType = ObjectOfAType.GetType()`. This sentence is correct if object declared within the same assembly. – scor4er Mar 27 '18 at 12:44