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# 元祖,最佳的临时变量。

相关推荐
yaoxin5211236 分钟前
390. Java IO API - WatchDir 示例
java·前端·python
Halo_tjn2 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色2 小时前
java 利用redis来限制用户频繁点击
java·开发语言
报错小能手2 小时前
Swift 并发 Combine响应式框架
开发语言·ios·swift
万法若空2 小时前
C++ <memory> 库全方位详解
开发语言·c++
代码中介商2 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫2 小时前
C++之string(OJ练习)
开发语言·c++·stl
freshman_y2 小时前
一篇介绍C语言中二级指针和二维数组的文章
c语言·开发语言
-Marks-3 小时前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本