这是为了序列化和反序列化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
回来时“类型的值无法转换为'1维数组”
我认为我在正确的轨道上进行实例化,就像我正在使用'testOrderPart1',但我不知道如何将其链接到我的anotherTest.orderpart
请帮忙!
答案 0 :(得分:1)
您必须首先初始化数组属性:
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)
也适用于序列化。