【发布时间】:2016-07-19 07:38:59
【问题描述】:
我有一个类似于this one 的问题。
我的问题如下:
我有一些基本消息为所有其他消息提供基本方法
public class BaseMessage : ISpecificMessage1
{
public MsgType {get;set;} //enum
public abstract void read(BinaryReader br);
public abstract void write(BinaryWriter bw);
}
并且我有覆盖这些基本方法的派生类。即。
public class MessageType1 : BaseMessage
{
public override void read(BinaryReader br)
{
//Do the read..
}
public override void write(BinaryWriter bw)
{
//Do the write..
}
}
我还有其他更深层次的派生类再次覆盖这些方法
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..
}
}
我现在的问题是我正在运行一个消息解析器,我调用一个静态方法来删除包装器,决定消息的类型并将消息作为 BaseMessage 返回
public static BaseMessage extractMessage(byte[] msg)
{
//Remove header... get type...
switch(MsgType)
{
case type1_ext:
return new MessageType1_Extended()
//etc...
}
}
当我在提取的消息上调用 .read() 时,深度大于 2 级的类仅调用 BaseMessage 之上级别的读取方法。即。 MessageType1_extended 将为 MessageType1 执行读取。
通过阅读之前链接的问题,我明白为什么会发生这种情况,但我的问题是是否有任何方法可以解决这个问题。 有什么方法可以转换为它的类型并调用它自己的覆盖方法而不将类型硬编码为 ((MessageType1_extended)extractedMessage).read(); ??
谢谢。
【问题讨论】:
-
你的问题对我来说有点不清楚。
read()中是否有base.read()和write()中的base.write()? -
为了清晰起见更新了帖子。每个类的每次读写都不一样
-
您将不得不显示未能调用正确方法的代码。你正在做的应该工作