AddEventHandler using reflection

前端 未结 3 1891
心在旅途
心在旅途 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:38

    Here's a sample showing how to attach an event using reflection:

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            var eventInfo = p.GetType().GetEvent("TestEvent");
            var methodInfo = p.GetType().GetMethod("TestMethod");
            Delegate handler = 
                 Delegate.CreateDelegate(eventInfo.EventHandlerType, 
                                         p, 
                                         methodInfo);
            eventInfo.AddEventHandler(p, handler);
    
            p.Test();
        }
    
        public event Func TestEvent;
    
        public string TestMethod()
        {
            return "Hello World";
        }
    
        public void Test()
        {
            if (TestEvent != null)
            {
                Console.WriteLine(TestEvent());
            }
        }
    }
    

提交回复
热议问题