How to remove yourself from an event handler?

后端 未结 2 421
挽巷
挽巷 2021-01-12 02:02

What I want to do is basically remove a function from an event, without knowing the function\'s name.

I have a FileSystemWatcher. If a file is created/

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-12 02:32

    Steps to remove event handler with lambda expression:

    public partial class Form1 : Form
    {
        private dynamic myEventHandler;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            myEventHandler = new System.EventHandler((sender2, e2) => this.button1_Click(sender, e, "Hi there"));
            this.button1.Click += myEventHandler;
        }
    
        private void button1_Click(object sender, EventArgs e, string additionalInfo)
        {
            MessageBox.Show(additionalInfo);
            button1.Click -= myEventHandler;
        }
    }
    

提交回复
热议问题