自己学习过程中的一点笔记:



using System;
using System.Collections.Generic;
using System.Text;

namespace TestApp
{
class Program
{
public static void Main(string[] args)
{
Test tst = new Test();
tst.InitAddEvent(AddEvent); // 传递事件处理函数地址
tst.CallAddEvent(); // 触发事件

Console.Read(); // 暂停程序
}

// 加法事件
public static int AddEvent(object sender, EventArgs e)
{
AddEventData ad = (AddEventData)e;
int c = ad.a + ad.b;
Console.WriteLine("触发事件AddEvent, a+b={0}", c);
return c;
}
}

public class Test
{
// 事件委托,即事件原型定义
public delegate int AddEventDelegate(object sender, EventArgs e);

// 事件对象
public event AddEventDelegate OnAddEvent = null;

// 初始化事件
public void InitAddEvent(AddEventDelegate addEvent)
{
this.OnAddEvent = addEvent;
//this.OnAddEvent += new AddEventDelegate(addEvent);
}

// 触发事件
public void CallAddEvent()
{
if (OnAddEvent != null)
{
AddEventData ad = new AddEventData();
ad.a = 1;
ad.b = 99;
OnAddEvent(this, ad);
}
}
}

// 事件参数,必须继承类EventArgs
public class AddEventData:EventArgs
{
public int a;
public int b;
}
}