C#委托與事件的簡單使用


前言:上一篇博文從原理和定義的角度介紹了C#的委托和事件。本文通過一個簡單的小故事,來說明C#委托與事件的使用方法及其方便之處。

在閱讀本文之前,需要你對委托和事件的基本概念有所了解。如果你是初次接觸C#的委托與事件,請先閱讀:C#委托與事件初探

 

好了,故事開始了~

 

一.小考拉從前的生活

  從前有一只小考拉,她的生活中只有三樣東西:水,米飯和肉。她渴了就去拿水喝,餓了就去拿米飯和肉吃。而且,米飯和肉一定要一起吃(換作你也不會單吃一種吧^_^),於是代碼是這樣的

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace KoalaOldLife
 8 {
 9     class Koala
10     {
11         public void Water() { Console.WriteLine("Find Water"); }
12         public void Rice() { Console.WriteLine("Find Rice"); }
13         public void Meat() { Console.WriteLine("Find Meat"); }
14 
15         public void Need()
16         {
17             Water();
18             Rice();
19             Meat();
20         }
21     }
22 
23     class Program
24     {
25         static void Main(string[] args)
26         {
27             Koala koala = new Koala();
28             koala.Need();
29             Console.ReadKey();
30         }
31     }
32 }

  我們的關注點在Need函數(下同),因為Need函數表明了小考拉有需求的時候要怎樣做。小考拉先拿了水喝,然后拿了米飯和肉吃。

 

二.小考拉現在的生活

  終於有一天,小考拉覺得整天自己找東西吃太累了,於是她回到家,委托爸爸媽媽幫忙。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace KoalaLife
 8 {
 9     class Water
10     {
11         public void showWater() { Console.WriteLine("Here's the Water!"); }
12     }
13 
14     class Rice
15     {
16         public void showRice() { Console.WriteLine("Here's the rice"); }
17     }
18 
19     class Meat
20     {
21         public void showMeat() { Console.WriteLine("Here's the meat"); }
22     }
23 
24     delegate void Dad(); //定義委托
25     delegate void Mom();
26 
27     class Koala
28     {
29         public event Dad thirsty; //定義事件
30         public event Mom hungry;
31 
32         public void Need()
33         {
34             thirsty(); //調用事件
35             hungry();
36         }
37     }
38 
39     class Program
40     {
41         static void Main(string[] args)
42         {
43             Koala koala = new Koala();
44             koala.thirsty += (new Water()).showWater; //綁定事件對應的方法
45             koala.hungry += (new Rice()).showRice;
46             koala.hungry += (new Meat()).showMeat;
47 
48             koala.Need();
49             Console.ReadKey();
50         }
51     }
52 }

  從Need函數可以看出,小考拉說渴的時候爸爸會過來,說餓的時候媽媽會過來。但是最開始他們並不知道要拿什么東西給小考拉。所以在Main函數中,小考拉要提前告訴爸爸:我說渴的時候給我拿水;提前告訴媽媽:我說餓的時候給我拿米飯和肉。

  這樣一來,小考拉就不用自己找東西了,只需要提前告訴爸爸媽媽一次渴和餓的時候需要什么,然后直接喊“我渴了”,“我餓了”,爸爸媽媽就會來送東西給小考拉吃。小考拉就能有更多時間懶懶的睡覺啦zZ~

 

三.總結

  以上故事中,最開始只有對象(小考拉)和方法(水、米飯、肉)兩層。后來在對象和方法這兩層之間,加入了委托(爸爸媽媽),變為了三層,從而簡化思路。很明顯,這是因為,委托和事件幫助我們隱去了底層的一些細節,將細節封裝起來,從而簡化編程。

  我想,這又是面向對象思想的一個體現吧。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM