VB.Net Tutorial/Class Module/Class Serialization — различия между версиями

Материал из VB Эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 12:55, 26 мая 2010

Class Serialization

Imports System.Runtime.Serialization
Public Class Tester
    Public Shared Sub Main
        Dim newEmp As New Employee
        Dim outFile As IO.FileStream
        Dim formatter As New Formatters.Binary.BinaryFormatter
        newEmp.FullName = "John Doe"
        newEmp.HireDate = #11/7/2005#
        newEmp.Salary = 10000@
        outFile = New IO.FileStream("EmpData.dat",IO.FileMode.Create)
        formatter = New Formatters.Binary.BinaryFormatter
        formatter.Serialize(outFile, newEmp)
        outFile.Close()

        Dim oldEmp As Employee = Nothing
        Dim inFile As IO.FileStream
        inFile = New IO.FileStream("EmpData.dat",IO.FileMode.Open)
        formatter = New Formatters.Binary.BinaryFormatter
        oldEmp = CType(formatter.Deserialize(inFile), Employee)
        inFile.Close()
        Console.WriteLine(oldEmp.FullName)
        Console.WriteLine(oldEmp.HireDate.ToString())
        Console.WriteLine("Salaray: " & oldEmp.Salary.ToString())
    End Sub
End Class

<Serializable()> _
Public Class Employee
    Implements ISerializable
    Public FullName As String
    Public HireDate As Date
    Private CurrentSalary As Decimal
    Public Property Salary() As Decimal
        Get
            Return CurrentSalary
        End Get
        Set(ByVal value As Decimal)
            CurrentSalary = value
        End Set
    End Property
    Public Sub New()
    End Sub
    Public Sub New(ByVal info As SerializationInfo, _
          ByVal context As StreamingContext)
        FullName = info.GetString("FullName")
        HireDate = info.GetDateTime("HireDate")
        CurrentSalary = info.GetDecimal("Salary")
    End Sub
    Public Sub GetObjectData( _
          ByVal info As SerializationInfo, _
          ByVal context As StreamingContext) _
          Implements ISerializable.GetObjectData
        info.AddValue("FullName", FullName)
        info.AddValue("HireDate", HireDate)
        info.AddValue("Salary", CurrentSalary)
    End Sub
End Class
John Doe
07/11/2005 12:00:00 AM
Salaray: 10000