Binární serializace
Přidáno: 14.11.2008
Kategorie: Aplikace
Autor: Ondřej Linhart
Binární serializace je metodika, jakou se dá uložit a později obnovit libovolný serializovatelný typ. Za serializovatelný typ se považují základní datové typy a typy označené atributem <Serializable()>. Binární serializace narozdíl od XML serializace dokáže uložit a rekonstruovat kompletně celý typ včetně vnitřních (Private) proměnných.
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Threading
Module Module1
Sub Main()
Dim person As New Person("Ondřej")
Dim fileName = Path.GetTempFileName()
Dim formatter As New BinaryFormatter()
Using file As New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)
formatter.Serialize(file, person)
file.Seek(0, SeekOrigin.Begin)
Dim deserializedPerson = DirectCast(formatter.Deserialize(file), Person)
Debug.WriteLine(deserializedPerson.Equals(person))
End Using
End Sub
End Module
<Serializable()> Class Person
Implements IDeserializationCallback
Private _id As Guid
<NonSerialized()> Private _lock As ReaderWriterLock
Private _name As String
Public Sub New(ByVal name As String)
_id = Guid.NewGuid()
_lock = New ReaderWriterLock()
_name = name
End Sub
Public ReadOnly Property Id() As Guid
Get
Return _id
End Get
End Property
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_lock.AcquireWriterLock(Timeout.Infinite)
_name = value
_lock.ReleaseWriterLock()
End Set
End Property
Public Sub OnDeserialization(ByVal sender As Object) Implements System.Runtime.Serialization.IDeserializationCallback.OnDeserialization
_lock = New ReaderWriterLock()
End Sub
Public Overrides Function Equals(ByVal obj As Object) As Boolean
If TypeOf obj Is Person Then
Dim otherPerson = DirectCast(obj, Person)
If (Me._id = otherPerson._id) AndAlso (Me._name = otherPerson._name) Then
Return True
Else
Return False
End If
Else
Return False
End If
End Function
End Class