我正在尝试序列化一个类,然后将其反序列化为第二个类,以模仿未来对类结构的添加,所以我试图实现 ISerializable
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
<Serializable()> _
Public Class Serial
Implements ISerializable
Public Num1 As Integer
Public Num2 As Integer
Protected Sub New(ByVal Info As SerializationInfo, ByVal Context As StreamingContext)
With Info
Num1 = .GetInt32("Num1")
Num2 = .GetInt32("Num2")
End With
End Sub
Public Sub GetObjectData(info As System.Runtime.Serialization.SerializationInfo, context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
With info
.FullTypeName = "ObjectSerialization. Serial"
.AddValue("Num1", Num1)
.AddValue("Num2", Num2)
End With
End Sub
End Class
<Serializable()> _
Public Class Serial2
Implements ISerializable
Public Num1 As Integer
Public Num2 As Integer
Public Num3 As Integer
Protected Sub New(ByVal Info As SerializationInfo, ByVal Context As StreamingContext)
With Info
Num1 = .GetInt32("Num1")
Num2 = .GetInt32("Num2")
Num3 = .GetInt32("Num3")
End With
End Sub
Public Sub GetObjectData(info As System.Runtime.Serialization.SerializationInfo, context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
With info
.FullTypeName = "ObjectSerialization. Serial"
.AddValue("Num1", Num1)
.AddValue("Num2", Num2)
.AddValue("Num3", Num3)
End With
End Sub
End Class
当我尝试在下面的代码中反序列化时,发生异常(无法加载类型 ObjectSerialization。反序列化所需的序列号)。有人可以指出我正确的方向。
Dim s1 As New Serial
Dim s2 As New Serial2
s1.Num1 = 99
s1.Num2 = 500
Dim fs As New FileStream("DataFile.dat", FileMode.Create)
Dim formatter As New BinaryFormatter
Try
formatter.Serialize(fs, s1)
Catch ex As SerializationException
Console.WriteLine("Failed to serialize. Reason: " & ex.Message)
Finally
fs.Close()
End Try
fs = New FileStream("DataFile.dat", FileMode.Open)
Try
formatter = New BinaryFormatter
s2 = formatter.Deserialize(fs)
Catch ex As SerializationException
Console.WriteLine("Failed to deserialize. Reason: " & ex.Message)
Throw
Finally
fs.Close()
End Try
End Sub