C# Event

在C#建立Event有5步

一: 最外面声明Delegate:

delegate void MyEventHandler (int x, string y);

二:建立含有私有类的Event(被别人使用):

class MyClass()

{

  ...

  public event MyEventHandler MyEvent;  

  ...

}

三:建立class的实例(Subscribing to an event)

MyClass obj = new MyClass();

四:Listening to the event:

subscribe event: obj.MyEvent += handlerFunction;

stop listing:     obj.MyEvent -= handlerFunction;

 

五:Declare the function:注意要和delegate一致:

void handlerFunction(int x, string y) { ... }

This is the function taht's going to be called whenever that event happens

 

实例:

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace UsingEvent
 7 {
 8     public delegate void myEventHandler(string newValue);
 9     
10     class EventExample    //建立一个可以raise evnent的class,其他人可以用.因为是private的class所以外部使用需要一个
11     {
12         private string theValue;        //建立一个theValue,目的是一旦value变了就raise一个event
13         public event myEventHandler valueChanged;
14 
15         public string Val            //建立一个property,为了expose theValue
16         {
17             set            
18             {
19                 this.theValue = value;                    //赋值给内部theValue为外部付给property的任何值
20                 this.valueChanged(theValue);        //任何本class的实例subscribe to listening this event的会被告知value change了
21             }
22         }
23     }
24 
25     class Program
26     {
27         static void Main(string[] args)
28         {
29             EventExample myEvt = new EventExample();        //新建含有Event的EventExample类的实例
30             myEvt.valueChanged += new myEventHandler(myEvt_valueChanged);        //加载一个myEvt_valueChanged function给实例的event,这个会被IDE创建
31 
32             string str;
33             do
34             {
35                 str = Console.ReadLine();
36                 if (!str.Equals("exit"))
37                     myEvt.Val = str;        //trigger the Event
38 
39             } while (!str.Equals("exit"));
40         }
41 
42         static void myEvt_valueChanged(string newValue)        //这个会被IDE创建,创建的newValue和之前delegate的参数一样
43         {
44             Console.WriteLine("The value changed to {0}", newValue);
45         }
46     }
47 }

 

 

原文地址:https://www.cnblogs.com/shawnzxx/p/2664697.html