网上很多介绍C#事件处理机制的文章,但很多都太复杂,概念含混,比喻牵强,越看越看不懂……
其实哪有那么复杂。
看看下面这段代码,看不懂直接留言骂我,我绝不还口~!
public class Program
{
delegate void EventFunType(int x);//先定义一个事件处理程序的代理类型
class EventTester //这个是会发生这个事件的对象
{
public event EventFunType onEvent;//这个就是他的事件处理方法储存器,目前是空的
public void TestEvent()
{
onEvent?.Invoke(1);//这里是他触发事件的地方
}
}
static void Main(string[] args)
{
Console.WriteLine("hello");
EventTester tester = new EventTester();//建立对象
tester.onEvent += new EventFunType(PlusOne);//添加一个处理方法
tester.onEvent += new EventFunType(PlusTwo);//再添加一个处理方法
tester.TestEvent();//触发
Console.ReadKey();
void PlusOne(int x)//这是事件的处理代码
{
Console.WriteLine("{0} + 1 = {1}", x, x + 1);
}
void PlusTwo(int x)//这是另一个事件的处理代码
{
Console.WriteLine("{0} + 2 = {1}", x, x + 2);
}
}
}
546

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



