【问题标题】:VB.NET Serealize structure that contains lists包含列表的 VB.NET Serealize 结构
【发布时间】:2017-06-20 09:50:12
【问题描述】:

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

我有这个数据结构:

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)) 创建单独文件的情况下序列化预订集合?

谢谢!

【问题讨论】:

    标签: vb.net serialization struct xml-serialization ixmlserializable


    【解决方案1】:

    共享成员不会被序列化,因为序列化只是为了保存类/结构实例,而共享成员不是实例的一部分。

    向你的结构添加一个实例属性,你应该很高兴:

    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
    

    如果您希望将标签称为&lt;bookings&gt;,您只需将XmlArray attribute 应用于属性:

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

    【讨论】:

    • 很高兴能帮上忙!祝你的项目好运!
    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 2019-12-15
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 2021-07-28
    相关资源
    最近更新 更多