AddEventHandler using reflection

前端 未结 3 1897
心在旅途
心在旅途 2020-11-28 08:10

I have this piece of code that does not work:

public CartaoCidadao()
{
    InitializeComponent();

    object o = WebDAV.Classes.SCWatcher.LoadAssembly();
           


        
3条回答
  •  盖世英雄少女心
    2020-11-28 08:55

    When you say it doesn't work... what happens? Nothing? An exception?

    Thoughts:

    • are both the event and the handler public? If not, you'll need to pass suitable BindingFlags to the GetEvent / GetMethod calls.
    • does the signature of the handler match?

    Here's a working example (note I'm using a static handler, hence the null in Delegate.CreateDelegate):

    using System;
    using System.Reflection;
    class Test
    {
        public event EventHandler SomeEvent;
        public void OnSomeEvent()
        {
            if (SomeEvent != null) SomeEvent(this, EventArgs.Empty);
        }
        static void Main()
        {
            Test obj = new Test();
            EventInfo evt = obj.GetType().GetEvent("SomeEvent");
            MethodInfo handler = typeof(Test)
                .GetMethod("MyHandler");
            Delegate del = Delegate.CreateDelegate(
                evt.EventHandlerType, null, handler);
            evt.AddEventHandler(obj, del);
    
            obj.OnSomeEvent();
        }
    
        public static void MyHandler(object sender, EventArgs args)
        {
            Console.WriteLine("hi");
        }
    }
    

提交回复
热议问题