我在VB.NET中创建了一个自定义imagelist类,我想序列化/反序列化它。
Imports System.Xml.Serialization
<Serializable()>
Public Class clsImageList
Public Images As New List(Of clsImageItem)
Public Sub Add(ByVal uGUID As String, ByRef uImage As Image)
Dim nItem As New clsImageItem(uImage, uGUID)
Images.Add(nItem)
End Sub
Public Function Image(ByVal uIndex As Integer) As Image
Return Images.Item(uIndex).Image
End Function
End Class
Public Class clsImageItem
Public ReadOnly Property [Image] As Image
Private _sGUID As String
Public Sub New(uImage As Image, uGUID As String)
Image = uImage
_sGUID = uGUID
End Sub
End Class
使用常规ImageList,我这样做:
Public Function ImageListToBytes(ByRef uImageList As ImageList) As Byte()
Try
Using ms As New MemoryStream
Dim bf As New BinaryFormatter()
bf.Serialize(ms, uImageList.ImageStream)
Return ms.ToArray
End Using
Catch ex As Exception
Debug.Assert(False)
Return Nothing
End Try
End Function
Public Sub BytesToImageList(ByRef uBytes() As Byte, ByRef uImageList As ImageList)
Using ms As New MemoryStream()
ms.Write(uBytes, 0, uBytes.Length)
ms.Seek(0, SeekOrigin.Begin)
Dim bf As New BinaryFormatter
uImageList.ImageStream = DirectCast(bf.Deserialize(ms), ImageListStreamer)
End Using
End Sub
有人能告诉我如何序列化/反序列化我的clsImageList吗?
答案 0 :(得分:2)
首先应该标记clsImageItem
Serializable
。
然后尝试序列化和反序列化clsImageList
类。所以在序列化和反序列化方法中,传递clsImageList
的实例并对其进行序列化和反序列化。
Public Function ImageListToBytes(ByRef c As clsImageList) As Byte()
Try
Using ms As New MemoryStream
Dim bf As New BinaryFormatter()
bf.Serialize(ms, c)
Return ms.ToArray
End Using
Catch ex As Exception
Debug.Assert(False)
Return Nothing
End Try
End Function
Public Sub BytesToImageList(ByRef uBytes() As Byte, ByRef c As clsImageList)
Using ms As New MemoryStream()
ms.Write(uBytes, 0, uBytes.Length)
ms.Seek(0, SeekOrigin.Begin)
Dim bf As New BinaryFormatter
c = DirectCast(bf.Deserialize(ms), clsImageList)
End Using
End Sub