使用数组和 Redim Preserve 的替代方法

Alternative to using Arrays and Redim Preserve

我只有一个主要要求,即一切都是可序列化的。

我最初想将 List 和构造函数与可传递的变量一起使用,这使得一切看起来都不错,但后来发现它们都不容易序列化。

所以,目前我正在使用一个数组 ReDim Preserve 但是什么是存储多个项目并且仍然能够序列化它们的好方法?每次我沿着一条路走下去,我似乎都会到达 limitation/dead 终点。

我有我的主要 class 'MARKFILE' 它包含一些 '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

代码有很多问题,开始时它不会像发布的那样编译:

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

我也会使用属性(如图所示)而不是字段。集合 class 也需要属性:

<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 中的内容 未标记为可序列化。


还有一些可以(应该)对集合进行的改进 class。与其公开 collection/List,不如在其上添加、删除、清除、计数、项目等类型的函数来实际 管理 列表,而不是仅仅保留它和把它暴露给世界。 Add 也可以重载以获取 Marker 对象。

似乎名称 属性 应该在小数据 class(标记)上而不是集合上。因为它是 (ReadOnly) 它是无用的,因为没有办法设置它。