我有一个字节数组,例如:
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".
知道为什么会这样吗?
答案 0 :(得分: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
基本上,您不能将任何反序列化为对象的实例。它必须是该对象的实际序列化版本。