VB.NET 序列化包含列表的结构

VB.NET Serealize structure that contains lists

我正在寻找一种方法来序列化包含不同类型对象(例如字符串、整数和集合)的结构。

我有这个数据结构:

Dim database as New mainStruct

<Serializable()> Structure mainStruct
    Public name As String
    Public address As String
    Public Shared bookings As IList(Of booking) = New List(Of booking)
End Structure

<Serializable()> Structure booking
    Public id As Integer
    Public category As String
    Public description As String
End Structure

运行 序列化程序:

    Dim fs As FileStream = New FileStream("x.bin", FileMode.OpenOrCreate)
    Dim serial As New XmlSerializer(GetType(mainStruct))
    serial.Serialize(fs, database)
    fs.Close()

输出只包含所有非集合变量如:

<?xml version="1.0"?>
  <mainStruct xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <name>foo</name>
  <address>bar</address>
</mainStruct>

如何在不使用 GetType(List(Of booking)) 创建单独文件的情况下序列化预订集合?

谢谢!

共享成员没有序列化,因为序列化就是保存一个class/structure实例,而共享成员不是部分一个实例。

将一个实例 属性 添加到您的结构中,您应该可以开始了:

Public Property bookingList As IList(Of booking)
    Get
        Return mainStruct.bookings
    End Get
    Set(value As IList(Of booking)
        mainStruct.bookings = value
    End Set
End Property

如果您希望标签被称为 <bookings>,您只需将 XmlArray attribute 应用于 属性:

<XmlArray("bookings")> _
Public Property bookingList As IList(Of booking)
    ...same code as above...
End Property