c#中的事件 event

事件 就是一系列的动作。比如,柚子表白事件,就有好几个动作:1.摆柚子 2.暖场舞蹈 3.拿话筒表白。

事件是由一系列动作组成,对理解事件的使用很关键。

那么动作是什么呢?动作就是函数,因为函数就是做什么,一个函数就是一个动作,反之亦然。因此,事件 由一系列函数组成的

那么,函数有大有小,把一系列的函数实体加入到事件中,是不明智的。我们就将函数的代表加入到事件中。什么是函数的代表呢?在C#中,有一个delegate (委托),它就是标记一个函数代表类的。

 1 namespace EventDemo  
 2 {  
 3   
 4 delegate void FunctionName();//declare a funtion delegate class 
 5 class EventClass      {  
 6     public event FunctionName someevent;//declare an event;the event based on function delegate;  
 7     public void Run()//the method that makes the event run; 
 8     {  
 9         someevent();//because someevent is function name,so,this fashion makes function run;
10     }  
11 }    
12 //following is some functions that should be used directly in future;  
13 //hence,i wrap them in a class;
14 class F       {  
15     public static void Arrange()  
16     {  
17         Console.WriteLine("the boy arranges the grapefuits");  
18     }  
19     public static void Dance()  
20     {  
21         Console.WriteLine("friends of the boy dance");  
22     }  
23     public static void Express()  
24     {  
25         Console.WriteLine("the boy sings "if you" " );  
26     }  
27 }  
28   
29 class Program    {  
30     public static void Main(string[] args)  
31     {    
32         EventClass myEvent = new EventClass();  
33         //add function name,namely,the function delegates, to the event;  
34        //someevent is the list of functions;and functions are represented by function delegates;</strong>  
35         myEvent.someevent += F.Dance;  
36         myEvent.someevent += F.Arrange;  
37         myEvent.someevent += F.Express;  
38         myEvent.Run(); //event occurs;  
39         Console.ReadKey(true);  
40     }   
41  }  
42 }

event既然是一系列函数的列表,也可以看作是方法。既然是方法,那么它就属于某个对象的。那么,它就应该定义在类里面。作为类的一个方法使用。函数列表的函数可以来自很多方面,只要是函数就可以了。

delegate与event的区别:

首先event其实也是一种delegate,为了区分,我们称一般的delegate为“纯delegate”。

纯delegate与event的关系类似于field与Property(实事上前者就是field,或者我们可以把event看成是一种特殊的Property)

在使用上,纯delegate几乎没有任何限制,而event则有严格的限制(只能用在 += 和 -= 的左边

event更面向对象一些。
当我们需要灵活时,直接使用纯delegate;反之,需要严格的控制时,使用event。
由于event不能使用赋值运算符,因此有时我们要求一个事件在任何时刻只能有一个响应方法时,我们使用纯delegate更为方便。

*****************************************************
*** No matter how far you go, looking back is also necessary. ***
*****************************************************
原文地址:https://www.cnblogs.com/gangle/p/9212662.html