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#中的委托和事件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了