首页 > Windows开发 > 详细

C#_event_事件

时间:2015-11-27 14:35:33      阅读:573      评论:0      收藏:0      [点我收藏+]

//-------------------事件---------------------------

技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _01事件理解
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Mp3Player mp3 = new Mp3Player();
14 
15             mp3.AfterPowerOn += ShowOn;
16             mp3.BeforePowerOff += ShowOff;
17 
18             mp3.PowerOn();
19             mp3.PowerOff();
20             Console.ReadKey();
21         }
22 
23 
24         static void ShowOn()
25         {
26             Console.WriteLine("播放开机动画");
27         }
28 
29        static void ShowOff()
30         {
31             Console.WriteLine("播放关机动画");
32         }
33 
34     }
35 
36 
37 
38 
39     public class Mp3Player
40     {
41 
42         //将委托前面  添加event 变成事件   那么 该委托只能在该类内部实现
43         //在类的外部不能调用该委托  
44 
45         //也就是  外部只能注册或删除已经注册的方法      不能自己去调用  
46         //调用只能是在这个类的内部
47 
48         //也就是委托添加event之后   再类的外部  就变成了  event   只能通过+=  -= 来注册 删除方法不能 加()执行
49 
50         public event Action AfterPowerOn;
51         public event Action BeforePowerOff;
52 
53         public void PowerOn()
54         {
55 
56             Console.WriteLine("开机...");
57 
58             //开机后执行委托   可以理解为事件
59             if (AfterPowerOn != null)
60             {
61                 AfterPowerOn();
62             }
63 
64             MusicStart();
65         }
66 
67         public void PowerOff()
68         {
69 
70                     MusicStop();
71 
72                     //关机前的委托调用   如果委托不为空的话   此处理解为 事件
73                     if (BeforePowerOff != null)
74                     {
75                         BeforePowerOff();
76                     }
77                     Console.WriteLine("关机");
78     
79         }
80 
81         private void MusicStart()
82         {
83             Console.WriteLine("开始播放music");
84         }
85 
86         private void MusicStop()
87         {
88             Console.WriteLine("Music stop...");
89         }
90     }
91 }
事件理解

 

C#_event_事件

原文:http://www.cnblogs.com/siyi/p/5000463.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!