1

I have a question similar to this one.

My problem is as follows:

I have some base messages that provide the base methods for all other messages

public class BaseMessage : ISpecificMessage1
{
    public MsgType {get;set;} //enum
    public abstract void read(BinaryReader br);
    public abstract void write(BinaryWriter bw);
}    

and I have derived classes that override these basic methods. ie.

public class MessageType1 : BaseMessage
{
    public override void read(BinaryReader br)
    {
         //Do the read..
    }
    public override void write(BinaryWriter bw)
    {
         //Do the write..
    }
}  

I have other derived classes a level deeper that override the methods again

public class MessageType1_Extended : MessageType1
{
    public override void read(BinaryReader br)
    {
         //Do the read different to MessageType1..
    }
    public override void write(BinaryWriter bw);
    {
         //Do the write different to MessageType1..
    }
} 

My problem at the moment is that I am running a message parser, and I call a static method to remove the wrapper, decide which type the message will be and return the message as BaseMessage

public static BaseMessage extractMessage(byte[] msg)
{
    //Remove header... get type...  
    switch(MsgType)
    {
          case type1_ext:
              return new MessageType1_Extended()
          //etc...
    }
}

When I call .read() on the extracted message, classes greater than 2 levels deep call only the read method for the level above BaseMessage.. Ie. MessageType1_extended will perform read for MessageType1.

I understand why this is happening from reading the earlier linked question, but my question is whether there is any way around this. Is there any way to cast to its type and call its own override method without hardcoding the type in as ((MessageType1_extended)extractedMessage).read(); ??

Thanks.

Community
  • 1
  • 1
Thumpers
  • 111
  • 1
  • 9

1 Answers1

0

You can dynamically invoke the method on the correct type via Reflection.

However it strikes me that the overall solution is ripe for a redesign. You likely should not be using the base class to return a new instance of its own type. It's not entirely clear to me from the question what overall problem you're trying to solve, but you might consider whether a Visitor pattern implementation would be more clean for generating the parsed message.

Alternatively you could use polymorphic recursion to have each class call its base class's extract method and build up a result as the values are returned.

hemp
  • 5,602
  • 29
  • 43