在 vb.net 中将 byte[] 转换为对象



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

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".

知道为什么会这样吗?

你有一个字节数组:

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

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

最新更新