C # delegate description and explanation

Commission is a function declaration, but there is no function body, it can refer to different functions for different purposes, the real thing to deal with other people.
The easiest way below:
Example 1:

private void button3_Click(object sender, EventArgs e)
        {
            Set set_deg = new Set(set2);
            set_deg(80);
        }
        public void set2(int value)
        {
            progressBar1.Value = value; 
        }

Example 2:

public delegate string rename(string name);
        public string get_rename(rename rename,string name)
        {
            return "final name:" + rename(name);
        }
        public string test(string name)
        {
            return "rename:"+name;
        }
        private void button7_Click(object sender, EventArgs e)
        {
            rename rename=new rename(test);
            string final_name = get_rename(rename, "刘洪方");
            MessageBox.Show(final_name);
        }

When using multiple threads scenario, you need to invoke thread to call the delegate control window where, implementation below:

public void set(int value)
        {
            progressBar1.Value = value;
        }
private void button2_Click(object sender, EventArgs e)
        {
            ThreadStart ts = new ThreadStart(run);
            Thread thread = new Thread(ts);
            thread.Start();
        }
public void run()
        {
            for (int i = 1; i <= 100; i++)
            {
                Thread.Sleep(100);
                if (this.InvokeRequired)
                {
                    Set set_deg = new Set(set);
                    this.Invoke(set_deg, new object[] { i });
                }
                else
                {
                    set(i);
                }                
            }
        }
Published 48 original articles · won praise 3 · views 20000 +

Guess you like

Origin blog.csdn.net/chscomfaner/article/details/103729882