如何在F#反序列化期间实例化子类

时间:2017-12-02 20:38:33

标签: inheritance f# polymorphism deserialization

我有一个字节数组,我希望将其反序列化为F#中的具体类。第一个字节由“类型”组成,可用于推断期望的消息类型。可能有许多消息类型,它们是提供常用方法的基类的子类,例如:

/// The base message class
type public BaseMessage() =
    member val MessageType:uint8 = 0uy with get, set

    with
        static member ReadHeader(br:BinaryReader) =
            br.ReadByte()

        static member FromStream(br:BinaryReader) =
            let messageType = BaseMessage.ReadHeader(br)

            BaseMessage(MessageType = messageType)

/// The first message type
type public SubMessageA() =
    inherit BaseMessage()

    member val Desc = "" with get, set

    with
        static member FromStream(br:BinaryReader) =
            let messageType = BaseMessage.ReadHeader(br)
            let chars = Encoding.ASCII.GetChars(br.ReadBytes(4))

            new SubMessageA(MessageType = messageType,
                Desc = new string(chars))    

/// The second message type
type public SubMessageB() =
    inherit BaseMessage()

    member val Value = 0 with get, set

    with
        static member FromStream(br:BinaryReader) =
            let messageType = BaseMessage.ReadHeader(br)
            let value = br.ReadInt32()

            new SubMessageB(MessageType = messageType,
                Value = value)

现在的问题是:上面的方法要求我通过一些额外的Factory在消息类型之外实现某种模式匹配。有一个更好的方法吗?感觉继承应该能够避免像行为这样的'switch语句'并自动处理这种情况,但我不确定如何。

或者我可以在基类中包含一些包含模式匹配的常用方法,但那时违反了开放式主体 - 理想情况下我希望能够处理额外的类型,而不必触及基类!

我意识到这不完全是惯用的F#但是出于各种原因我需要坚持这里的课程。谢谢你的建议!

0 个答案:

没有答案