// 模拟从网络端读取协议 public void SimulateReadDataFromNet() { const int MAX = 5; Random r = new Random(); int cnt = 10; while (--cnt > 0) { // 模拟读取协议id int id = r.Next() % MAX; Type t = ProtocolDict.GetProtocolType(id); if (t != null) { BaseProtocol p = Activator.CreateInstance(t) as BaseProtocol; if (p != null) { // 模拟读取数据并设置内容 p.sth = "123123123"; // 然后在模拟派发收到的协议 SimulateDispatch(p); } } else { Console.WriteLine("无效的协议号:" + id); } } }
public Test() { // 注册协议 ProtocolDict.Register(1, typeof(Protocol1)); ProtocolDict.Register(2, typeof(Protocol2)); // 注册协议处理函数 dispatcher.Register <Protocol1>(OnProtocol1); dispatcher.Register <Protocol2>(OnProtocol2); }