Net Core教程

C# 事件简单示例

本文主要是介绍C# 事件简单示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
 1 using System;
 2 using System.Reflection;
 3 
 4 namespace ConsoleApp1
 5 {
 6     class Program
 7     {
 8         // 自定义委托
 9         public delegate void TestHandler(string msg);
10         // 使用自定义委托定义事件
11         public static event TestHandler TestEvent;
12 
13         static void TrigerEvent(string msg)
14         {
15             if (TestEvent != null)
16             {
17                 TestEvent(msg);
18             }
19         }
20         static void Man1(string msg)
21         {
22             Console.WriteLine(MethodBase.GetCurrentMethod().Name + " recv msg: " + msg);
23         }
24         static void Man2(string msg)
25         {
26             Console.WriteLine(MethodBase.GetCurrentMethod().Name + " recv msg: " + msg);
27         }
28         static void Man3(string msg)
29         {
30             Console.WriteLine(MethodBase.GetCurrentMethod().Name + " recv msg: " + msg);
31         }
32         static void Main(string[] args)
33         {
34             //加入事件订阅
35             TestEvent += new TestHandler(Man1);
36             TestEvent += new TestHandler(Man2);
37             TestEvent += new TestHandler(Man3);
38             TrigerEvent("is test event triger [1] ");
39 
40             //移除事件订阅
41             TestEvent -= new TestHandler(Man2);
42             TrigerEvent("is test event triger [2] ");
43 
44             Console.ReadKey();
45         }
46     }
47 }
运行结果

 


 


                    
这篇关于C# 事件简单示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!