C# 事件和委托(鸿门宴示例)
做事的思想应是先整体后局部,总分总。这篇博文有很好的写程序的思路,值得学习。
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 发动攻击。。。");
}
}
}
}
输出:
首领举左杯。
B 发动攻击。。。
=============
首领摔杯。
B 发动攻击。。。
C 发动攻击。。。
请按任意键继续. . .
参考:
1.link-01 // 分分钟用上C#中的委托和事件
浙公网安备 33010602011771号