C#在程序中定义和使用自定义事件可以分为以下几个步骤:
步骤1:在类中定义事件
复制代码
1
2
3
4
5
6
7
8
9
10
11using System; public class TestClass { //.... public event EventHandler TestEvent }
步骤2:定义事件参数
注意:事件参数类TestEventArgs继承自System.EventArgs
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13using System; public class TestEventArgs : EventArgs { public TestEventArgs() : base() { } public string Message { get; set; } }
步骤3:在TestClass 引发事件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public class TestClass { // 这个方法引发事件 public void RaiseTestEvent(string message) { if (TestEvent == null) return; TestEvent(this, new TestEventArgs { Message = message }); } public event EventHandler TestEvent; }
步骤4:使用事件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49class Program { static void Main(string[] args) { TestClass tc = new TestClass(); // 挂接事件处理方法 tc.TestEvent += Tc_TestEvent; Console.WriteLine("按任意键引发事件"); Console.ReadKey(); // 引发事件 tc.RaiseTestEvent("通过事件参数传递的字符串"); Console.WriteLine("按任意键退出"); Console.ReadKey(); } private static void Tc_TestEvent(object sender, EventArgs e) { // 将事件参数强制转换为TestEventArgs TestEventArgs te = (TestEventArgs)e; // 显示事件参数中的Message Console.WriteLine(te.Message); } }
完整的程序如下
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71using System; public class TestClass { public void RaiseTestEvent(string message) { if (TestEvent == null) return; TestEvent(this, new TestEventArgs { Message = message }); } public event EventHandler TestEvent; } public class TestEventArgs : EventArgs { public TestEventArgs() : base() { } public string Message { get; set; } } class Program { static void Main(string[] args) { TestClass tc = new TestClass(); tc.TestEvent += Tc_TestEvent; Console.WriteLine("按任意键引发事件"); Console.ReadKey(); tc.RaiseTestEvent("通过事件参数传递的字符串"); Console.WriteLine("按任意键退出"); Console.ReadKey(); } private static void Tc_TestEvent(object sender, EventArgs e) { TestEventArgs te = (TestEventArgs)e; Console.WriteLine(te.Message); } }
最后
以上就是狂野黑猫最近收集整理的关于c#在程序中定义和使用自定义事件方法总结的全部内容,更多相关c#在程序中定义和使用自定义事件方法总结内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复