C#的委託

委託:顧名思義,讓別人幫你辦件事。委託是C#實現回調函數的一種機制。可能有人會問了,回調函數是個啥???dom

舉個例子:我如今是一家公司的老闆,公司如今在招聘.NET工程師,咱們有一個小姐姐專門負責接受求職者投遞的簡歷,我就告訴這個小姐姐,一旦收到新的簡歷就轉發給我一份。ide

這個例子裏小姐姐要作的工做:給我轉發一份簡歷(回調函數裏的操做),就是一個回調函數的做用。一旦有了知足條件(收到了新的簡歷),小姐姐就會轉發給我(觸發回調函數函數

以上文章 轉載爲 千金不如一默  如下爲原創this


 

 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();

下面爲一個委託演示spa

 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
相關文章
相關標籤/搜索