【问题标题】:Solutions for derived class and 'shadowing'派生类和“阴影”的解决方案
【发布时间】: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()
  • 为了清晰起见更新了帖子。每个类的每次读写都不一样
  • 您将不得不显示未能调用正确方法的代码。你正在做的应该工作

标签: c# .net


【解决方案1】:

您可以通过反射动态调用正确类型的方法。

然而,让我感到震惊的是,重新设计的整体解决方案已经成熟。您可能不应该使用基类来返回其自己类型的新实例。从这个问题中我并不完全清楚您要解决的总体问题是什么,但您可能会考虑使用访问者模式实现是否会更干净地生成解析的消息。

或者,您可以使用多态递归让每个类调用其基类的提取方法并在返回值时构建结果。

【讨论】:

    猜你喜欢
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 2021-07-01
    • 2015-10-14
    • 2014-09-04
    相关资源
    最近更新 更多