事件可通过对委托施用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;
- }
- }
本文介绍如何在 C# 中使用事件机制,包括声明委托、定义事件及事件的订阅与触发过程。通过一个长任务进度通知的例子展示了事件的实际应用。
1万+

被折叠的 条评论
为什么被折叠?



