123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- using System;
- namespace EventDemo
- {
- public delegate void ProcessDelegate(object sender, EventArgs e);
- class Program
- {
-
- public event ProcessDelegate ProcessEvent;
- static void Main(string[] args)
- {
- // 方式1 委托方式创建事件
- Swim swim = new Swim();//实例化发布者
- MyClass myClass = new MyClass();//实例化订阅者
- myClass.EventABS += new MyClass.DelegateABS<string>(swim.You);//事件的固定格式 事件名+= new 委托(发布者的方法)
- myClass.OK("大家好!");
- // 方式2 EventArgs 创建
- /* 第一步执行 */
- Test t = new Test();
- /* 关联事件方法,相当于寻找到了委托人 */
- t.ProcessEvent += new ProcessDelegate(t_ProcessEvent);
- /* 进入Process方法 */
- Console.WriteLine(t.Process());
- //方式3
- //实例化发布者
- MailManager mm = new MailManager();
- //向事件登记回调方法
- Fax f = new Fax(mm);
- mm.SimulateNewMail("a", "b", "Hello World!");
- Console.ReadKey();
- }
- static void t_ProcessEvent(object sender, EventArgs e)
- {
- Test t = (Test)sender;
- t.Text1 = "Hello";
- t.Text2 = "World";
- }
- }
- public class Test {
-
- public string Text1 { get; set; }
- public string Text2 { get; set; }
- public event ProcessDelegate ProcessEvent;
- void ProcessAction(object sender, EventArgs e)
- {
- //if (ProcessEvent == null)
- // ProcessEvent += new ProcessDelegate(t_ProcessEvent);
- ProcessEvent(sender, e);
- }
- //如果没有自己指定关联方法,将会调用该方法抛出错误
- //void t_ProcessEvent(object sender, EventArgs e)
- //{
- // throw new Exception("The method or operation is not implemented.");
- //}
- void OnProcess()
- {
- ProcessAction(this, EventArgs.Empty);
- }
- public string Process()
- {
- OnProcess();
- return Text1 + Text2;
- }
- }
- class MyClass //定一个订阅者的类
- {
- //定义一个委托
- public delegate void DelegateABS<T >(T a);
- //定义一个事件
- public event DelegateABS<string > EventABS;
- //定义一个方法
- public void OK(string a )
- {
- EventABS(a);//调用事件
- }
- }
- class Swim//定义一个发布者
- {
- public void You(string a )
- {
- Console.WriteLine(a+"我喜欢游泳");
- }
- }
- }
|