C# 发布和订阅2
using System;
namespace ConsoleApp6
{
class Program
{
/*
背景:由于委托能引用方法,且能链接和删除其他委托对象
步骤:
①定义委托类型,并在发布者类中定义一个类型的共有成员
②在订阅者类中定义委托处理方法
③订阅者对象将其事件处理方法链接到发布者对象的委托成员(一个委托类型的引用)上。
④发布者对象在特定的情况下“激发”委托操作,从而自动调用订阅者对象的委托处理方法、
*/
static void Main(string[] args)
{
//创建学校铃声类
SchoolRing sr = new SchoolRing();
//创建学生实例
Students ss = new Students();
//订阅铃声委托
ss.SubscribeToRing(sr);
Console.WriteLine("请输入铃声参数(1表示上课;2表示下课)");
//打铃动作
sr.Jow(Convert.ToInt32(Console.ReadLine()));
Console.ReadLine();
}
}
/// <summary>
/// 声明一个委托类型
/// </summary>
/// <param name="ringKind"></param>
public delegate void RingEvent(int ringKind);
/// <summary>
/// 学校的铃声
/// </summary>
public class SchoolRing
{
public event RingEvent OnBellSound;//委托发布
//(插入知识点:添加event 以保证事件订阅可靠性,在发布委托的定义中加上event)
//读取输入,并且做出判断
public void Jow(int ringKind)
{
if (ringKind == 1 || ringKind == 2)
{
Console.WriteLine(ringKind==1?"":"");
///不等于空,说明它已订阅了具体的方法
if (OnBellSound!=null)
{
//回调OnBellSound委托所订阅(引用)的具体方法
OnBellSound(ringKind);
}
}
else
{
Console.WriteLine("这个铃声参数不正确");
}
}
}
/// <summary>
/// 学生类
/// </summary>
public class Students
{
public void SubscribeToRing(SchoolRing schoolRing)
{
schoolRing.OnBellSound +=SchoolJow;
}
private void SchoolJow(int ringKind)
{
if(ringKind==2)
{
Console.WriteLine("开始课间休息");
}
else if(ringKind==1)
{
Console.WriteLine("开始认真学习");
}
}
public void CancelSubscribe(SchoolRing schoolRing)
{
schoolRing.OnBellSound -= SchoolJow;
}
}
}
转载:https://blog.csdn.net/Linlietao0587/article/details/112131243
本文来自博客园,作者:.net&new,转载请注明原文链接:https://www.cnblogs.com/wugh8726254/p/16365462.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现