0

这是为了序列化和反序列化 Xml 对象

<XmlRoot("orderadd")>
<Serializable()> _
Public Class clsSMsgRequestMessage
    <XmlElementAttribute()> Public Property ordertype() As String
    <XmlElementAttribute()> Public Property vehicleid() As String
    <XmlElementAttribute()> Public Property orderpriority() As String
    <XmlElementAttribute("orderpart")> Public Property orderpart() As RequestMessageOrderaddOrderpart()
    <XmlAttributeAttribute()> Public Property clientid() As String
    <XmlAttributeAttribute()> Public Property transactionid() As String
    <XmlAttributeAttribute()> Public Property numberoforderparts() As String

    Public Sub New()
    End Sub
End Class

Public Class RequestMessageOrderaddOrderpart
    <XmlElementAttribute()> Public Property operation() As String
    <XmlElementAttribute()> Public Property location() As String
    <XmlElementAttribute()> Public Property loadtype() As String
    <XmlAttributeAttribute()> Public Property orderpartnumber() As String

    Public Sub New()
    End Sub

End Class

这适用于反序列化,但现在我正在尝试正确创建此对象,以便可以将其序列化回 XML 对象。

Dim anotherTest As clsSMsgRequestMessage = New clsSMsgRequestMessage()
Dim testOrderPart1 As New RequestMessageOrderaddOrderpart


anotherTest.clientid = "data"
anotherTest.orderpriority = "data"
anotherTest.ordertype = "data"
anotherTest.transactionid = "data"
anotherTest.vehicleid = "data"
anotherTest.numberoforderparts = "data"

testOrderPart1.loadtype = "data"
testOrderPart1.location = "data"
testOrderPart1.operation = "data"
testOrderPart1.orderpartnumber = "data"


anotherTest.orderpart(0) = testOrderPart1

这里的最后一行不起作用,因为 anotherTest.orderpart(0) 尚未实例化。但我不知道如何实例化它,因为

anotherTest.orderpart(0) = New RequestMessageOrderaddOrderPart

仍然返回“对象引用未设置为对象的实例”。

anotherTest.orderpart = New RequestMessageOrderaddOrderPart

返回“类型的值不能转换为'一维数组”

我认为我在自己实例化它方面走在了正确的轨道上,就像我对'testOrderPart1'所做的那样,但我不知道如何将它链接到我的 anotherTest.orderpart

请帮忙!

4

1 回答 1

2

您必须首先初始化您的数组属性:

anotherTest.orderpart = New RequestMessageOrderaddOrderPart(10) {}

10是数组大小。

之后,您将能够设置第一个数组元素:

anotherTest.orderpart(0) = New RequestMessageOrderaddOrderPart

更新

但是,我认为您应该将您的财产声明更改为List(Of RequestMessageOrderaddOrderPart). 使用列表,您不必指定项目数:

anotherTest.orderpart = New List(Of RequestMessageOrderaddOrderPart)()

添加项目非常简单:

anotherTest.orderpart.Add(new RequestMessageOrderaddOrderPart())

而且您仍然可以使用索引器获取/修改项目:

Dim firstItem = anotherTest.orderpart(0)

当然,该项目必须先使用Add方法插入。

List(Of T)序列化也可以正常工作。

于 2013-03-29T12:16:50.747 回答