vb.net的序列化

定义一个可以序列化的类;必须为公共字段、属性、方法;必须有一个公共的构造方法存在。
Public Class UnitsSystem
'试验类型名
Public TestTypeName As String
'试验类型号
Public TestTypeBh As String
'''
''' 本试验类型所具有的所有单位体系名称
'''

'''
Public UnitsSystemName As List(Of String)
'''
''' 纪录单位和系数的结构体
'''

'''
Public Structure UnitsSet
Dim UnitName As String
Dim UnitCoefficient As Single
End Structure
'''
''' 单位体系集合(记录了当前试验类型所有的单位体系详细信息)
'''

'''
Public UnitsSystemCollection As List(Of List(Of UnitsSet))
Public Sub New()


End Sub
Public Sub AddNew()
UnitsSystemName = New List(Of String)
UnitsSystemCollection = New List(Of List(Of UnitsSet))
End Sub
End Class

Imports System.IO
Imports System.Xml.Serialization
Imports System.Xml.Serialization.XmlSerializer


1.XML的序列化:
'''
''' 填充类,并序列化成文件
'''

''' 序列化成的文件名
''' 试验类型名
''' 试验类型编号
''' 单位体系名称
''' 一个单位体系集合
'''
Private Sub AddClassAndSerializationFile(ByVal FileName As String, ByVal TestTypeName As String, ByVal TestTypeBh As String, ByRef List As List(Of UnitsSet), Optional ByVal UnitSystemName As String = "标准单位体系")
Dim UnitSystemObject As UnitsSystem.UnitsSystem = DeSerializationFile(FileName)
'赋值单位体系
UnitSystemObject.TestTypeName = TestTypeName
UnitSystemObject.TestTypeBh = TestTypeBh
UnitSystemObject.UnitsSystemName.Add(UnitSystemName)
UnitSystemObject.UnitsSystemCollection.Add(List)
SerializationObject(FileName, UnitSystemObject)
UnitSystemObject = Nothing
End Sub
'''
''' 序列化
'''

'''
'''
'''
Private Sub SerializationObject(ByVal FileName As String, ByRef UnitSystemObject As UnitsSystem.UnitsSystem)
Dim writer As New System.Xml.Serialization.XmlSerializer(GetType(UnitsSystem.UnitsSystem))
Dim file As New System.IO.StreamWriter(FileName)
writer.Serialize(file, UnitSystemObject)
file.Close()
End Sub
'''
''' 反序列化文件并返回单位体系的一个对象
'''

''' 反序列化的文件名
''' 返回一个单位体系对象
'''
Private Function DeSerializationFile(ByVal FileName As String) As UnitsSystem.UnitsSystem
If System.IO.File.Exists(FileName) = False Then
Dim UnitSystemObject As New UnitsSystem.UnitsSystem
UnitSystemObject.AddNew()
Return UnitSystemObject
End If
Return DeSerializationObject(FileName)
End Function
'''
''' 反序列化
'''

'''
'''
'''
Private Function DeSerializationObject(ByVal FileName As String)
Dim reader As New System.Xml.Serialization.XmlSerializer(GetType(UnitsSystem.UnitsSystem))
Dim file As New System.IO.StreamReader(filename)
Dim UnitSystemObject As UnitsSystem.UnitsSystem
UnitSystemObject = CType(reader.Deserialize(file), UnitsSystem.UnitsSystem)
file.Close()
Return UnitSystemObject
End Function
对于结构体作为泛型list的一个子项;赋值这样做
Dim NodeUnit As UnitsSet
NodeUnit.UnitName = YesDW
NodeUnit.UnitCoefficient = Convert.ToSingle(YesXS)
UnitSystemObject.UnitsSystemCollection.Item(0).Item(i) = NodeUnit

你可能感兴趣的:(vb.net的序列化)