C# 简单模拟 程序内部 消息订阅发布功能

文章目录

前言

我想做个简单的消息发布订阅功能,但是发现好像没有现成的工具类。要么就是Mqtt这种消息订阅发布。但是我只想程序内部进行消息订阅发布,进行程序的解耦。那没办法了,只能自己上了

模拟消息订阅发布

在Utils 的MessageHelper

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetCore.Utils
{
    public class MessageHelper
    {
        public static List<Message> Messages = new List<Message>();

        /// <summary>
        /// 消息订阅
        /// </summary>
        public static void Subscribe(string topic,string key, Action<object> action)
        {
            var model = Messages.Where(item => item.Topic == topic && item.Key == key).FirstOrDefault();
            if (model == null)
            {
                model = new Message()
                {
                    Topic = topic,
                    Key = key,

                };

                Messages.Add(model);
            }

            model.Actions += action;

        }

        /// <summary>
        /// 消息推送
        /// </summary>
        public static void Publish(string topic,string key,object value)
        {
            var model = Messages.Where(item => item.Topic == topic && item.Key == key).FirstOrDefault();
            if (model != null)
            {
                model.Actions(value);
            }

        }

    }

    public class Message
    {
        public string Topic { get; set; }

        public string Key { get; set; }

        public Action<object> Actions { get; set; }
    }
}

使用

csharp 复制代码
static void Main(string[] args)
{
     MessageHelper.Subscribe("Topic1", "key1", (res) =>
     {
         var _res = ((string Name, int Age))res;
         Console.WriteLine(_res.ToString());
         Console.WriteLine("我被调用了1");
     });
     MessageHelper.Subscribe("Topic2", "key1", (res) =>
     {
         Console.WriteLine("我被调用了2");

     });
     MessageHelper.Subscribe("Topic3", "key1", (res) =>
     {
         Console.WriteLine("我被调用了3");

     });
     MessageHelper.Subscribe("Topic4", "key1", (res) =>
     {
         Console.WriteLine("我被调用了4");

     });
     MessageHelper.Publish("Topic1","key1",(Name:"嘟嘟",Sex:"12"));
     Console.ReadLine();
 }

注意事项

这里我用了元祖来进行临时变量的传值。元祖如何使用请看我的另一篇文章。元祖用来做临时变量特别好用

C# 元祖,最佳的临时变量。

相关推荐
sunshine22 girl几秒前
Java学习五 面向对象高级5 内部类1
java·学习
weixin_4407305020 分钟前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
sugarzhangnotes1 小时前
【无标题】
开发语言·人工智能·python
geovindu1 小时前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
samble1 小时前
从零搭建灌装监控系统(十):生产追溯,条码触发自动记录
c#·wpf·mvvm·modbus·工业控制
用户1305180712151 小时前
JDBC学习DAY2:从Statement到PreparedStatement
java
蛋蛋的就会顺顺的2 小时前
hot100——矩阵
java·数据结构·算法·leetcode·力扣
周杰偷奶茶2 小时前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
橙子圆1233 小时前
JUC之集合类不安全
java·开发语言
阿里嘎多学长3 小时前
2026-09-29 GitHub 热点项目精选
开发语言·程序员·github·代码托管