C# - 事件

/// <summary>
/// 自定义事件-步骤:
/// 1、声明关于事件的委托
/// 2、声明事件
/// 3、编写触发事件的方法
/// 4、创建事件处理程序
/// 5、注册事件处理程序
/// 6、在适当的条件下出发事件
/// </summary>

 

 

Dog.cs代码:

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 using System.Threading.Tasks;

 6 

 7 namespace 事件

 8 {

 9     public class Dog

10     {

11         //1、声明关于事件的委托                   :发送事件的发送者    :事件本身的参数

12         public delegate void AlarmEvenHandler(object sender, EventArgs e);

13 

14         //2、声明事件

15         public event AlarmEvenHandler Alarm;

16 

17         //3、编写触发事件的方法

18         public void OnAlarm()

19         {

20             if (Alarm != null)

21             {

22                 Console.WriteLine("\n狗报警,有小偷进来了………………\n");

23                 //寻找事件

24                 this.Alarm(this, new EventArgs());

25             }

26         }

27     }

28 }

 

 

Host.cs代码:

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 using System.Threading.Tasks;

 6 

 7 namespace 事件

 8 {

 9     public class Host

10     {

11         //4、编写事件处理方法

12         public void HostHandleAlarm(object sender, EventArgs e)

13         {

14             Console.WriteLine("主人:抓住小偷!");

15         }

16 

17         //5、注册时间处理方法

18         public Host(Dog dog)

19         {

20             dog.Alarm += new Dog.AlarmEvenHandler(HostHandleAlarm);

21         }

22     }

23 }

 

 

 

Program.cs代码:

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 using System.Threading.Tasks;

 6 

 7 namespace 事件

 8 {

 9     class Program

10     {

11         //6、触发事件

12         static void Main(string[] args)

13         {

14             Dog dog = new Dog();

15 

16             Host host = new Host(dog);

17 

18             Console.WriteLine("小偷进入………………");

19 

20             dog.OnAlarm();

21 

22             Console.ReadKey();

23         }

24     }

25 }

 

你可能感兴趣的:(C#)