Serialize a collection of objects
I'm trying to serialize a collection of a certain type of class...
I keep getting a Reflection error when I attempt to serialize with the code below... with the two classes below. I can sucessfully serialze the SalesRep class, but not its collection class... I CAN SUCESSFULLY serialize it to a BinaryFormatter ...and retrieve.. but not when using XMLSerializer...
VB Code:
Dim gwhiz As Xml.Serialization.XmlSerializer = New Xml.Serialization.XmlSerializer(GetType(SalesRepCollection))
Dim rep1 As SalesRep = New SalesRep(12, "John", "Labrizzi")
Dim rep2 As SalesRep = New SalesRep(5, "Eddie", "Gasser")
Dim myReps As SalesRepCollection = New SalesRepCollection()
myReps.Add(rep1)
myReps.Add(rep2)
dim fs as System.IO.FileStream = New System.IO.FileStream("C:\sales.xml", IO.FileMode.Create)
gwhiz.Serialize(fs, myReps)
fs.Close()
Here is the SalesRep Class:
VB Code:
<Serializable()> Public Class SalesRep
Public Sub New()
End Sub
Public Sub New(ByVal RepID As Int32, ByVal RepFirstName As String, _
ByVal RepLastName As String, Optional ByVal RepMiddleName As String = Nothing)
sRepID = RepID
sRepFName = RepFirstName
sRepMName = RepMiddleName
sRepLName = RepLastName
End Sub
Private sRepID As Int32
Private sRepFName As String
Private sRepMName As String
Private sRepLName As String
Public Property SalesRepId() As Int32
Get
Return sRepID
End Get
Set(ByVal Value As Int32)
sRepID = Value
End Set
End Property
Public Property FirstName() As String
Get
Return sRepFName
End Get
Set(ByVal Value As String)
sRepFName = Value
End Set
End Property
Public Property MiddleName() As String
Get
Return sRepMName
End Get
Set(ByVal Value As String)
sRepMName = Value
End Set
End Property
Public Property LastName() As String
Get
Return sRepLName
End Get
Set(ByVal Value As String)
sRepLName = Value
End Set
End Property
Here's the SalesRep collection class:
VB Code:
Option Strict Off
<Serializable()> Public Class SalesRepCollection
Inherits System.Collections.CollectionBase
Public Function Add(ByVal Salesman As SalesRep) As Integer
' Invokes Add method of the List object to add a object.
Return List.Add(Salesman)
End Function
Public Sub New()
End Sub
Public Sub Remove(ByVal index As Integer)
If index > Count - 1 Or index < 0 Then
Else
' Invokes the RemoveAt method of the List object.
List.RemoveAt(index)
End If
End Sub
'
Public Function GetItem(ByVal index As Integer) As SalesRep
Return CType(List.Item(index), SalesRep)
End Function
Public Sub SetItem(ByVal index As Integer, ByVal SalesMan As SalesRep)
List.Item(index) = CType(SalesMan, SalesRep)
End Sub