C# 事件和委托(鸿门宴示例)

来自网上的一片博文

悟:做事的思想应是先整体后局部,总分总。这篇博文有很好的写程序的思路,值得学习。

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;

namespace LianXi_事件和委托
{
class Program
{
public delegate void RaiseEventHandler(string hand);
public delegate void FallEventHandler();
static void Main(string[] args)
{
A a = new A();
B b = new B(a);
C c = new C(a);

a.Raise("左");

Console.WriteLine("=============");
a.Fall();
}

public class A
{
public event RaiseEventHandler RaiseEvent;
public event FallEventHandler FallEvent;
public void Raise(string hand)
{
Console.WriteLine("首领举{0}杯。", hand);
if (RaiseEvent != null)
{
RaiseEvent(hand);
}
}
public void Fall()
{
Console.WriteLine("首领摔杯。");
if (FallEvent != null)
{
FallEvent();
}
}
}
public class B
{
private A a;
public B (A a)
{
this.a = a;
a.FallEvent += a_FallEvent;
a.RaiseEvent += a_RaiseEvent;

}

public void a_RaiseEvent(string hand)
{
if (hand == "左")
{
Attack();
}
}
public void a_FallEvent()
{
Attack();
}
public void Attack()
{
Console.WriteLine("B 发动攻击。。。");
}
}
public class C
{
private A a;
public C(A a)
{
this.a = a;
a.FallEvent += a_FallEvent;
a.RaiseEvent += a_RaiseEvent;
}
public void a_RaiseEvent(string hand)
{
if (hand == "右")
{
Attack();
}
}
public void a_FallEvent()
{
Attack();
}
public void Attack()
{
Console.WriteLine("C 发动攻击。。。");
}
}
}
}

输出:

1
2
3
4
5
6
7
首领举左杯。
B 发动攻击。。。
=============
首领摔杯。
B 发动攻击。。。
C 发动攻击。。。
请按任意键继续. . .




参考:
1.link-01 // 分分钟用上C#中的委托和事件

感谢支持!