事件可通过对委托施用event关键字来创建。
首先,声明一个委托;
delegate void StateChangedDelegate(object state);
然后,将事件声明为类的一个成员
public event StateChangedDelegate OnStateChanged;
最后,对事件感兴趣的类可以订阅事件,像多播委托类似。
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace EventSample
- {
- class Program
- {
- static void Main(string[] args)
- {
- LongTask lt = new LongTask();
- lt.OnNotifyProgress += new LongTask.NotifyProgressDelegate(lt_OnNotifyProgress);
- lt.PerformTask();
- }
- static void lt_OnNotifyProgress(ProgressArgs pa)
- {
- Console.WriteLine("Progress completed {0}.", pa.proComplete);
- }
- }
- class LongTask
- {
- public delegate void NotifyProgressDelegate(ProgressArgs pa);
- public event NotifyProgressDelegate OnNotifyProgress;
- public void PerformTask()
- {
- for (int i = 0; i != 100; i++)
- {
- if (i % 10 == 0)
- {
- OnNotifyProgress(new ProgressArgs(i));
- }
- }
- }
- }
- class ProgressArgs
- {
- public ProgressArgs(int proComplete)
- {
- this.proComplete = proComplete;
- }
- public int proComplete;
- }
- }