在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一個event13 public event myEventHandler valueChanged;14 15 public string Val //建立一個property,為了expose theValue16 {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 Program26 {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 do34 {35 str = Console.ReadLine();36 if (!str.Equals("exit"))37 myEvt.Val = str; //trigger the Event38 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 }