Add Event Handler using Reflection ? / Get object of type?

我与影子孤独终老i 提交于 2021-01-28 07:27:47

问题


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 )

回答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.



来源:https://stackoverflow.com/questions/49512369/add-event-handler-using-reflection-get-object-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!