当通过tcp套接字接收消息时,是否有更好的方法来进行类型检查

本文关键字:方法 更好 检查 类型 是否 tcp 套接字 消息 | 更新日期: 2023-09-27 18:30:10

一开始我只是在做if语句来检查发送的对象的类型,但如果你有一堆不同类型的消息对象,那可能会很痛苦。然后我想了想,我做了一个被调用的事件,然后当某个类型监听该事件时,每个函数都会做一些事情,当它被调用时,它会检查它

if语句的方式

   //code for after message received - if you need the code for listening for the message i can give it but i don't see a need
   Type msgType = msgObj.getType();
   if(msgType == messageType1){
        //do stuff
   }
   else if(msgType == messageType2){
        //do more stuff
    }
   // and so on

正如你所看到的,如果你有很多不同类型的消息,这可能会很糟糕

事件的方式

   private delegate messageEvent(object message);
   public event messageEvent onMessage;
   //code after message received
   onMessage(msgObj);

   // sample function that will listen for the onMessage event
   private void onMessage(object message){
        if(message.getType() == typeForThisFunction){
              //do somthing
        }
   }

正如你所看到的,这比if语句简单一点,但要确保所有内容都在侦听仍然很困难,如果有很多不同类型的消息,并同时检查它们,也会发现问题。

有没有一种更容易的方法?

当通过tcp套接字接收消息时,是否有更好的方法来进行类型检查

有一种常用的方法不仅更方便,而且可以在运行时配置(而if/else或等效的switch只能在编译时配置):制作Dictionary

var dict = new Dictionary<Type, Action<object>>
           {
               { typeof(SomeMessage), m => this.Process((SomeMessage)m) },
               { typeof(OtherMessage), m => this.Process((OtherMessage)m) },
           };

字典中的值只是一个例子,您可以根据自己的要求选择不同的做法。

类似于基于事件的方法的其他方法也同样有效。例如,您可以让您的业务逻辑保存类的对象集合,例如:

 interface IMessageProcessor
 {
     bool WantsToHandle(MessageBaseClass message);
 }
 class SomeMessageProcessor : IMessageProcessor { /* ...*/ }
 class OtherMessageProcessor : IMessageProcessor { /* ...*/ }

MessageBaseClass应该包含关于消息的"类型"的信息;当然,您可以只传递object并对对象的运行时类型进行筛选,但速度会慢一些。当消息到达时,您依次将其提供给每个IMessageProcessor