C#的委托

委托:顾名思义,让别人帮你办件事。委托是C#实现回调函数的一种机制。可能有人会问了,回调函数是个啥???

举个例子:我现在是一家公司的老板,公司现在在招聘.NET工程师,我们有一个小姐姐专门负责接受求职者投递的简历,我就告诉这个小姐姐,一旦收到新的简历就转发给我一份。

这个例子里小姐姐要做的工作:给我转发一份简历(回调函数里的操作),就是一个回调函数的作用。一旦有了满足条件(收到了新的简历),小姐姐就会转发给我(触发回调函数

以上文章 转载为 千金不如一默  以下为原创


 1 Action<string> CR = obj => MessageBox.Show(obj);//给他一个临时的obj作为接受值然后callaction的方法obj来接收收到的值
 2 Action<string> CRA = new Action<string>(showmsg);//也可以这样写 
 3 new Action<object>((object err) =>MessageBox.Show((string)err))("");
 4 CR("1");
 5 //action委托用来代理一个任意过程给过程一个值=>指向一个方法然后就可以调用//action没有返回值
 6 
 7 //Delegate无法在过程里声明必须声明全局
 8 
 9 //Delegate委托是最广泛的他支持全部过程但是并没有上下两个精简和效率
10 
11 MyDelegate mydelegate = new MyDelegate(s => GetStr(s));
12 MyDelegate mydelegateA = new MyDelegate(GetStr);//也可以这样写
13 string get = mydelegate(1);
14 
15 
16 //func 委托用来执行一个没有传参且有返回值的过程
17 Func<string> getstr = new Func<string>(showmsgA);
18 string getAAA = getstr();

下面为一个委托演示

 1         private void button1_Click(object sender, EventArgs e)
 2         {
 3             label1.Text = "";
 4             PictureBox pic = new PictureBox();
 5 
 6             pic.Width = 0;
 7             pic.Height = this.Height;
 8             pic.BackColor = Color.Red;
 9             this.Controls.Add(pic);
10             label1.Parent = this;
11             label1.SendToBack();
12             if (maxthread == 0) {
13 
14                 new Thread(() => {
15                     maxthread++;
16                     while (pic.Width < this.Width)
17                     {
18                         Thread.Sleep(1);
19                         pic.BeginInvoke(new Action(() => { pic.Width = pic.Width + 2; }));
20                     }
21                     Thread.Sleep(1000);
22                     CheckForIllegalCrossThreadCalls = false;
23                     Random rd = new Random();
24                     int getjl = rd.Next(0, 100);
25                     //100
26 
27                     if (getjl < 5)
28                     {
29                         label1.Text = "中大奖";
30 
31                     }
32 
33                     if (getjl < 10 && getjl >5)
34                     {
35                         label1.Text = "电冰箱";
36 
37                     }
38 
39                     if (getjl <= 100 && getjl > 10)
40                     {
41                         label1.Text = "未中奖";
42 
43                     }
44 
45                     while (pic.Width > 0)
46                 {
47                     pic.BackColor = Color.Black;
48                     Thread.Sleep(1);
49                     pic.BeginInvoke(new Action(() => { pic.Width = pic.Width - 2; }));
50                 }
51 
52 
53                 maxthread--;
54 
55             }).Start();
56 
57             }
View Code
原文地址:https://www.cnblogs.com/hack747/p/12259285.html