C# Dynamic Event Subscription

前端 未结 9 1891
無奈伤痛
無奈伤痛 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:38

    It's not a completely general solution, but if all your events are of the form void Foo(object o, T args) , where T derives from EventArgs, then you can use delegate contravariance to get away with it. Like this (where the signature of KeyDown is not the same as that of Click) :

        public Form1()
        {
            Button b = new Button();
            TextBox tb = new TextBox();
    
            this.Controls.Add(b);
            this.Controls.Add(tb);
            WireUp(b, "Click", "Clickbutton");
            WireUp(tb, "KeyDown", "Clickbutton");
        }
    
        void WireUp(object o, string eventname, string methodname)
        {
            EventInfo ei = o.GetType().GetEvent(eventname);
    
            MethodInfo mi = this.GetType().GetMethod(methodname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
    
            Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);
    
            ei.AddEventHandler(o, del);
    
        }
        void Clickbutton(object sender, System.EventArgs e)
        {
            MessageBox.Show("hello!");
        }
    

提交回复
热议问题