我只有一个主要要求,一切都是可序列化的。
我最初想要使用带有可传递变量的List和Constructors,这些变量使得一切看起来都不错,但后来发现它们都不容易序列化。
所以,目前我正在使用一个数组和ReDim Preserve
但是什么是存储多个项目并且仍然可以序列化它们的好方法?每次我走上一条路,我似乎都遇到了限制/死路。
我有我的主要课程'MARKFILE',它包含许多'标记'
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
答案 0 :(得分:4)
代码存在许多问题,从它开始不会编译为已发布:
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!
所以,首先启用Option Strict。
要使List(of Marker)
可序列化,您需要添加一个属性:
<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
我也会使用属性(如图所示)而不是Fields。集合类也需要该属性:
<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
序列化数据很简单:
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
您可能遇到的错误不是List
,而是List
中的标记为可序列化。
还可以(应该)对集合类进行一些改进。它不应该暴露集合/列表,而应该在其上添加,删除,清除,计数,项目等类型函数来实际管理列表,而不是仅仅抓住它并将其暴露给世界。可以重载添加以获取Marker
对象。
看起来名称属性应该在小数据类(Marker)而不是集合上。因为它(ReadOnly)它没用,因为没有办法设置它。