利用多播委托可以消除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 编辑 

少有人走的路


















