【问题标题】:BinaryFormatter.Serialize adding 28 to byte array lengthBinaryFormatter.Serialize 将 28 添加到字节数组长度
【发布时间】:2017-01-01 07:28:12
【问题描述】:

我有以下代码 sn-p,它在 TcpClient 网络流上接收消息,其中可能包含 obj 类型形式的一些内容,并尝试将其序列化为字节数组:

let readStreamToFile (client:TcpClient) outputPath =
    let formatter = new BinaryFormatter()

    try
        let message = (formatter.Deserialize (client.GetStream ())) :?> Message
        match message.Type with
        | FileTransfer ->
            match message.Content with
            | Some content ->
                let bytesContent = 
                    use mStream = new MemoryStream()
                    formatter.Serialize (mStream, content)
                    mStream.ToArray ()

                File.WriteAllBytes (outputPath, bytesContent)
            | None ->
                failwith "There was no content in the FileSync message!!!"
        | _ ->
            ()
    with
    | :? InvalidCastException as ex ->
        failwith "Message format unknown!!!"

不幸的是,当我调试这段代码时,我可以看到接收到的内容很好,长度为46,但在formatter.Serialize (mStream, content)之后对mStream.ToArray ()的调用长度为74。也就是说,它添加了28 项长度为 46 的实际数组之前。这 28 项也不为空,有些包含值。

这正常吗?如何使bytesContent 始终与我的obj content 相同?

【问题讨论】:

  • 如果你只想要字节,为什么要打电话给formatter.Serialize,为什么不直接抢字节呢?
  • BinaryFormatter 对对象的类型信息和序列化值进行编码。在反序列化时重建对象需要类型信息。
  • @TnTinMn 领先我一分钟。额外的 28 个字节是类型信息,采用 BinaryFormatter 可以理解的某种格式——这样当它反序列化数据时,就能够生成正确类型的对象。
  • 正如前面提到的 cmets 所说,这正是你告诉它做的事情。更大的问题是你想要什么以及为什么。
  • 如果@TnTinMn 想添加它作为答案,我很乐意接受。我猜这是因为我没有在序列化之前调用反序列化。

标签: .net arrays serialization f# stream


【解决方案1】:

BinaryFormatter 对对象的类型信息和序列化值进行编码。在反序列化时重建对象需要类型信息。额外的字节是类型信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    相关资源
    最近更新 更多