C#的事件机制
上一篇 / 下一篇 2008-03-12 14:29:57 / 个人分类:C# Programming
%sZ%V-^Y&jc&RS9q%iFy0/*
0W#UGSM0 * 我已经在该例中把创建,发送,触发,处理事件的过程用一步步的步骤描述出来了,不过现在还是迷迷糊糊的,有不明白的地方请见谅.
o2b"?u
]#gO(ltA/K0 */51Testing软件测试网&f(W;[
d(z&p7E;VO
6U3Av&s;Ac051Testing软件测试网O[g#]b _8w~
v(~b6XS
using System;51Testing软件测试网#W_1Dz O.]._l"eZ@
//命名空间51Testing软件测试网*rsA^
BV(iW.E
namespace testEventApp
7lh6c]_I"G k0{51Testing软件测试网|L,F0@Z.Cd]G
/*第一步:创建一个委托*/
J2[%N,L$l8W0 //定义委托Class2_Event_Handler51Testing软件测试网eBN\k
public delegate void Class2_Event_Handler(object sender, string strEventArg);51Testing软件测试网gs
~~cw;GS8u
y\8M+ZM5?F3O x0 /// <summary>51Testing软件测试网t+twC*iD5n
/// Class1 的摘要说明。
k:@I ?qx0 /// </summary>
Dw(q3jJ7R9gY0/*=======================================================================
*Rr}Y7HijJ0 事件接收方类
!\ D,K1k
Vv0=======================================================================*/
@ml
p&U8~:J_&A(w0 //定义类Class151Testing软件测试网M;O{*H#|ik$?)g
class Class151Testing软件测试网1ZAFx%dz
{
}2id]
| M0 //创建类Class1的默认构造器51Testing软件测试网{V,v%X'DF GrK
public Class1()51Testing软件测试网T0D6W*X,@Gi
{51Testing软件测试网|8xSV-jg
r+X`8o)j
Console.WriteLine ("Class1>>>创建一个Class1对象!");
9L
i_-r)J0t,z0 }
\g P
V$K f(?V,}-~Q5c-MV0/*第四步:编写事件处理函数,该函数要具有与第一步中创建的委托相同的签名51Testing软件测试网MtWcVk;bH!O
*/51Testing软件测试网SyQYtT$[9X U4Fq
private void On_Class2Event(object sender, string strEventArg)
o nTBB9O6dPOE0 { //Class2中事件发生时的处理函数51Testing软件测试网Ho1G7m5[8X%\7CV
Console.WriteLine("Class1>>>收到Class2中的事件:" + strEventArg);
;S&oy$D4\e_7]0 if (strEventArg == "exit")
(}A$}
kLqVmsVq0 {51Testing软件测试网!\A&YoOa
Class2 senderRef = (Class2)sender;51Testing软件测试网4t;o,|&l9q
//取消事件处理函数与Class2中事件的关联51Testing软件测试网:A6vV
D1`.i'~;k]
senderRef.Class2_Event -= new Class2_Event_Handler(this.On_Class2Event);51Testing软件测试网0^.PF.i-f.L
Console.WriteLine("Class1>>>不再接收Class2的事件!输入exit退出!");
j]P0Q!DI/F2i0 }
JR,G3Uq a%a]0^0 }
^U7Nx:G0 /// <summary>
d/i/h2j@_0 /// 应用程序的主入口点。51Testing软件测试网Y&B/kk]+WQz&L4nxL
/// </summary>51Testing软件测试网]KQ/s5or
[STAThread]51Testing软件测试网v0TJ6N{;s
static void Main(string[] args)51Testing软件测试网;`m
y\*m7q|&m2G
{