多播委托消除if或者swich,模拟交换机的广播

利用多播委托可以消除if或者switch。

其原理如下:


多播委托类似于交换机的广播。

192.168.1.255这个地址在C类私有网络中是一个广播地址。广播地址用于向本地网络中的所有设备发送数据包。
当一个设备向192.168.1.255发送数据包时,该网络中的所有设备都会收到这个数据包。

下面代码中的if判断则是在广播的接收端加入了协议判断,只有符合协议的站点进行了回应。



源码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        public enum 语种
        {
            英语 = 0, 汉语, 俄语
        }
        //Action<语种,>
        public delegate string SayDelegate(语种 yz, string user);
        static void Main(string[] args)
        {
            SayDelegate dlg;
            string user = "小德";
            dlg = new 英语say().Say;
            dlg += new 汉语say().Say;
            dlg += new 俄语say().Say;

            SayHello(dlg, 语种.汉语, "小德");

            Console.ReadKey();
        }

        static void SayHello(SayDelegate dlg,语种 yz, string user)
        {
            var method = dlg.GetInvocationList();
            foreach (var item in method)
            {
                var res = (item as SayDelegate).Invoke(yz, user);
                if (res.Length > 0)
                {
                    Console.WriteLine(res);break;
                }
            }
        }


        interface ISay
        {
           
           string Say(语种 yz, string user);
        }

        public class 英语say : ISay
        {
          

            public string Say(语种 yz, string user)
            {
                if (yz == 语种.英语)
                    return ($"hello,{user}");
                else
                    return "";

            }
        }

        public class 汉语say : ISay
        {
        
            public string Say(语种 yz, string user)
            {
                if (yz == 语种.汉语)
                    return ($"你好,{user}");
                else
                    return "";
            }
        }

        public class 俄语say : ISay
        {
          
            public string Say(语种 yz, string user)
            {
                if (yz == 语种.俄语)
                    return ($"aaaa,{user}");
                else
                    return "";
            }
        }


    }
}



--------------------- 

作者:hackpig

来源:www.skcircle.com

版权声明:本文为博主原创文章,转载请附上博文链接!




本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:
本帖最后由 勇哥,很想停止 于 2023-12-14 10:29:12 编辑

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«    2024年4月    »
1234567
891011121314
15161718192021
22232425262728
2930
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864