【问题标题】:Converting byte[] to object in vb.net将 byte[] 转换为 vb.net 中的对象
【发布时间】:2016-03-09 22:33:54
【问题描述】:

我有一个字节数组,例如:

Dim byteArray(10) as Byte

byteArray(0) = 1
byteArray(1) = 2
byteArray(2) = 3
...
byteArray(9) = 10

我正在尝试将其转换为对象但没有成功。我在这里阅读了很多关于如何做到这一点的帖子,所以我有以下功能:

Public Shared Function ByteArrayToObject(ByVal arrBytes As Byte()) As Object

    Using ms As New MemoryStream()
        Dim binForm As New BinaryFormatter()
        ms.Write(arrBytes, 0, arrBytes.Length)
        ms.Seek(0, SeekOrigin.Begin)
        Dim obj As Object = DirectCast(binForm.Deserialize(ms), Object)

        Return obj
    End Using

End Function

但在执行 DirectCast 时,我收到一个异常,或多或少(从西班牙语翻译):

"SerializationException was unhandled: End of sequence reached before terminating analysis".

知道为什么会这样吗?

【问题讨论】:

  • 字节序列1 2 3 4 5 6 7 8 9 10 听起来不像Object 的序列化实例。你到底想在这里做什么?
  • 你试过CType(byteArray, Object)吗?
  • 为什么不创建一个可序列化的结构或类?

标签: vb.net serialization memorystream binaryformatter directcast


【解决方案1】:

你有一个字节数组:

Dim byteArray(10) as Byte

byteArray(0) = 1
byteArray(1) = 2
byteArray(2) = 3
...
byteArray(9) = 10

这个字节流是什么:

1 2 3 4 5 6 7 8 9 10

但是你没有有一个序列化的对象。这是您的代码所假设的:

Dim obj As Object = DirectCast(binForm.Deserialize(ms), Object)

该流无法反序列化为Object 的实例,因为它不是Object 的序列化实例。但这是(或者至少在我的测试中是在我的机器上):

0 1 0 0 0 255 255 255 255 1 0 0 0 0 0 0 0 4 1 0 0 0 13 83 121 115 116 101 109 46 79 98 106 101 99 116 0 0 0 0 11

基本上,您不能将 anything 反序列化为对象的实例。它必须是该对象的实际序列化版本。

【讨论】:

    猜你喜欢
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2020-02-16
    • 2019-11-03
    • 1970-01-01
    • 2021-10-20
    • 2013-01-06
    相关资源
    最近更新 更多