C# Dynamic Event Subscription

前端 未结 9 1911
無奈伤痛
無奈伤痛 2020-12-01 03:09

How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do some

9条回答
  •  一个人的身影
    2020-12-01 03:29

    public TestForm()
    {
        Button b = new Button();
    
        this.Controls.Add(b);
    
        MethodInfo method = typeof(TestForm).GetMethod("Clickbutton",
        BindingFlags.NonPublic | BindingFlags.Instance);
        Type type = typeof(EventHandler);
    
        Delegate handler = Delegate.CreateDelegate(type, this, method);
    
        EventInfo eventInfo = cbo.GetType().GetEvent("Click");
    
        eventInfo.AddEventHandler(b, handler);
    
    }
    
    void Clickbutton(object sender, System.EventArgs e)
    {
        // Code here
    }
    

提交回复
热议问题