我正在尝试实现对象初始化器。所有的类都是由其他人创建的。我不能改变。
我有一个类Ins.vb
,它有一个list作为属性
Partial Public Class Ins
Private itemField As Item1
Private sizeCodeListField() As SizeCode 'This is the property
Public Property Item() As Item1
Get
Return Me.itemField
End Get
Set
Me.itemField = value
End Set
End Property
Public Property SizeCodeList() As SizeCode()
Get
Return Me.sizeCodeListField
End Get
Set
Me.sizeCodeListField = value
End Set
End Property
End Class
Item1.vb
Public Partial Class Item1
Private codeField As String
Public Property Code() As String
Get
Return Me.codeField
End Get
Set
Me.codeField = value
End Set
End Property
End Class
SizeCode.vb
Partial Public Class SizeCode
Private sizeCode1Field As String
Private sizeCodeDescriptionField As String
Public Property SizeCode1() As String
Get
Return Me.sizeCode1Field
End Get
Set
Me.sizeCode1Field = value
End Set
End Property
Public Property SizeCodeDescription() As String
Get
Return Me.sizeCodeDescriptionField
End Get
Set
Me.sizeCodeDescriptionField = value
End Set
End Property
End Class
这是我如何尝试做对象初始化
Dim myVar = New Ins _
With {.Item = New Item1 With {.Code = "I"},
.SizeCodeList = New SizeCode With {.SizeCode1 = "S", .SizeCodeDescription = "Description"}} 'I am getting an error here
错误是Value of type 'SizeCode' cannot be converted to 'SizeCode()'
我不知道如何实现这一点,我卡住了。
你的语法应该是这样的:
Dim myVar = New Ins _
With {.Item = New Item1 With {.Code = "I"},
.SizeCodeList = New SizeCode() {New SizeCode With {.SizeCode1 = "S", .SizeCodeDescription = "Description"}}}
您正在将. sizecodelist初始化为一个SizeCode,但它应该是一个列表。我没有测试它,但这应该工作,我认为:
Dim myVar = New Ins With
{.Item = New Item1 With {.Code = "I"},
.SizeCodeList = New List(Of SizeCode)}
Dim newSizeCode As New SizeCode With {.SizeCode1 = "S", .SizeCodeDescription = "Description"}
myvar.SizeCodeList.add(newSizeCode)