Reputation: 396
I have just one main requirement, that everything is Serializable.
I initially wanted to use List and Constructors with passable variables which made everything looked nice but then found out both those are not easily serializable.
So, currently I am using an Array and ReDim Preserve
but what is a good way to store multiple items and still be able to serialize them? Every time I go down one path I seem to hit a limitation/dead end.
I have my main class 'MARKFILE' and it contains a number of 'Markers'
Public Class MARKFILE
Private _Name As String
Public ReadOnly Property Name
Get
Return _Name
End Get
End Property
Public Property _Markers() As Marker()
Public Sub Add_Marker(ByRef Aa As String, ByRef Bb As String, Cc As Double)
Dim Mark As New Marker
Mark.A= Aa
Mark.B= Bb
Mark.C= Cc
If IsNothing(_Markers) Then
ReDim _Markers(0)
_Markers(_Markers.Length - 1) = Mark
Else
ReDim Preserve _Markers(_Markers.Length)
_Markers(_Markers.Length - 1) = Mark
End If
End Sub
End Class
Public Class Marker
Public A As String
Public B As String
Public C As String
Public D As String
End Class
Upvotes: 0
Views: 507
Reputation: 38875
There are a number of problems with the code, starting with it wont compile as posted:
Public Sub Add_Marker(ByRef Aa As String, ByRef Bb As String, Cc As Double)
...
Mark.C = Cc ' Mark.C is String, cannot assign Double To String!
So, first turn on Option Strict.
To make a List(of Marker)
serializable, you need to add an attribute:
<Serializable>
Public Class Marker
Public Property A As String
Public Property B As String
Public Property C As String
Public Property D As String
End Class
I would also use properties (as shown) rather than Fields. The collection class needs the attribute as well:
<Serializable>
Public Class Markers
Private _Name As String
Public ReadOnly Property Name As String
Get
Return _Name
End Get
End Property
Public Property Markers As List(Of Marker)
Public Sub New()
Markers = New List(Of Marker)
End Sub
Public Sub Add(Aa As String, Bb As String, Cc As String)
Markers.Add(New Marker With {.A = Aa, .B = Bb, .C = Cc})
End Sub
End Class
Serializing the data is simple:
Dim col As New Markers
col.Add("A", "B", "C")
Using fs As New FileStream("C:\temp\marks.bin", FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
bf.Serialize(fs, col)
End Using
The error you were likely getting was not about the List
but that the stuff in the List
was not marked as serializable.
There are also a number of refinements which could (should) be done to the collection class. Rather than exposing the collection/List, there should likely be Add, Remove, Clear, Count, Item etc type functions on it to actually manage the list rather than just hold onto it and expose it to the world. Add could be overloaded to take a Marker
object as well.
It also seems like the Name Property ought to be on the little data class (Marker) rather than the collection. As it is (ReadOnly) it is useless because there is no way to set it.
Upvotes: 4